码迷,mamicode.com
首页 > 其他好文 > 详细

react项目Bug:组件销毁清除监听(Can't perform a React state update on an unmounted component.)

时间:2020-03-28 18:28:12      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:bug   time   set   and   reac   mount   idt   项目   方法   

最近一直在做react项目,发现一个bug,困扰了我两天。

Can‘t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

稍稍翻译下:不能在已经被销毁的组件中调用setState()方案 

出现场景:跳转路由 当前组件被销毁 组件内部还存在异步操作对state的状态信息 比如http请求,定时器setTimeOut更新state

 

解决方法:

1、清除所有监听

componentWillUnmount() {
  this.setState = (state,callback)=>{ return; };
}

组件被销毁之前重写setState方法 不对状态做任何改变

或者定向取消某些监听即可,如下所示

 

2、定向清除个别监听

将定时器绑定到组件

技术图片

技术图片

 

react项目Bug:组件销毁清除监听(Can't perform a React state update on an unmounted component.)

标签:bug   time   set   and   reac   mount   idt   项目   方法   

原文地址:https://www.cnblogs.com/jianxian/p/12588369.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!