抛出问题:
首先抛出问题,有时开发过程中会遇到如下报错:
![b12410b6fd68c8844715bcfc3f8d25a9.png](https://i-blog.csdnimg.cn/blog_migrate/787af52f374afcc015439d7ac81d26a7.png)
Warning: 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.
翻译内容如下:
警告:无法对未安装的组件执行响应状态更新。这是一个禁止操作,但它表示应用程序内存泄漏。要修复,请取消componentwillunmount方法中的所有订阅和异步任务。
问题原因:
通常是 react 组件已经从 DOM 中移除,但是我们在组件中做的一些异步操作还未结束,如组件卸载之后依然调用了 this.setState()
,而此时我们已经将改组件dom移除,通常有以下两种情况:
- 设置了定时器setInterval 、setTimeout等, 在componentwillunmount之前没有清除掉;
- 异步请求
callback
在请求回来之前组件已经执行了componentwillunmount