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

最近一直在做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、定向清除个别监听

将定时器绑定到组件

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