使用reactjs遇到Warning: setState(...): Can only update a mounted or mounting component.

前端数据大部分来源于后端,需要向后端发起异步请求,而在使用reactjs的时候,如果这个组件最初加载的时候就发起这个异步请求,然后在返回结果中进行setState({}),这时候有可能会遇到这个警告:

Warning:setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component.This is a no-op.
Please check the code for the xxx component.

  

通常是因为组件并没有装载上便开始执行setState({}),这时候,我们可以在组件中写入:

componentWillMount(){
    this.mounted = true;
    this.getData();
}

componentWillUnmount() {
    this.mounted = false;
}

 

然后在异步请求返回结果后setState的时候进行判断:

if(this.mounted){
    this.setState({
    });
}

这个警告便消除了~

原文地址:https://www.cnblogs.com/mmykdbc/p/8651679.html