Can't call setState (or forceUpdate) on an unmounted component ——React 内存泄漏问题处理

在开发过程中,最近遇到一个错误

Can't call setState (or forceUpdate) on an unmounted component ——React 内存泄漏问题处理

大致意思:不能对于一个已经卸载的组件上使用setState改变状态,这将会造成应用的内存泄漏。

解决方法:在componentWillUNmount 阶段中取消所有的异步任务(例如:SetState操作)。

如果在react组件中设置了定制器或者在dom上绑定了事件,卸载组件时未清除定时器或未清除事件,或者在已经卸载的组件中设置setState,都会导致内存泄漏。我们可以利用钩子函数:componentWillUnmount() 进行定时器和事件的清除。避免组件的提前卸载(回调函数的setState改变的不是整个组件的状态)。

componentWillUnmount(){     //卸载组件前执行的钩子函数
    this.refs.btn.onclick = null;  //清除dom上绑定的事件
    clearInterval(this.timer);      //清除定时器
}

Can't call setState (or forceUpdate) on an unmounted component ——React 内存泄漏问题处理