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

   今天使用antdesign修改界面,select切换时遇到这个bug,一番搜索之后发现,关于react中切换路由时报以上错误,实际的原因是因为在组件挂载(mounted)之后进行了异步操作,比如ajax请求或者设置了定时器等,而你在callback中进行了setState操作。当你切换路由时,组件已经被卸载(unmounted)了,此时异步操作中callback还在执行,因此setState没有得到值。

解决方案一:在卸载的时候对所有的操作进行清除(例如:abort你的ajax请求或者清除定时器)

 1 componentDidMount = () => {
 2     //1.ajax请求
 3     $.ajax('你的请求',{})
 4         .then(res => {
 5             this.setState({
 6                 aa:true
 7             })
 8         })
 9         .catch(err => {})
10     //2.定时器
11     timer = setTimeout(() => {
12         //dosomething
13     },1000)
14 }
15 componentWillUnMount = () => {
16     //1.ajax请求
17     $.ajax.abort()
18     //2.定时器
19     clearTimeout(timer)
20 }

解决方案二:设置一个flag,当unmount的时候重置这个flag

 1 componentDidMount = () => {
 2     this._isMounted = true;
 3     $.ajax('你的请求',{})
 4         .then(res => {
 5             if(this._isMounted){
 6                 this.setState({
 7                     aa:true
 8                 })
 9             }
10         })
11         .catch(err => {})
12 }
13 componentWillUnMount = () => {
14     this._isMounted = false;
15 }

解决方案三:置空setState

 1 componentDidMount = () => {
 2     $.ajax('你的请求',{})
 3     .then(res => {
 4         this.setState({
 5             data: datas,
 6         });
 7     })
 8     .catch(error => {
 9 
10      });
11 }
12 componentWillUnmount = () => {
13     this.setState = (state,callback)=>{
14       return;
15     };
16 }

 

posted @ 2021-01-26 09:47  光何  阅读(291)  评论(0)    收藏  举报