react 偶现警告:
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. in BookInfo (created by Route)
原因
组件Unmount
之后依然调用 this.setState()
, 通常有两种情况。
- 设置了定时器setinterval 或者递归setTimeout。 unmonut之前没有清除掉。
- 异步请求
callback
在请求回来之前组件已经unmount
解决办法
1. 对于定时器
在componentWillUnmount
生命周期, 必须clear调用定时器
2.对于异步请求
两种解决方案。
-
方案一 设置标志位在挂载是为true,
componentWillUnmount
时设为false,然后在异步调用的callback里面做判断 -
方案二 在
componentWillUnmount
取消异步请求
一个老外的解说视频https://www.youtube.com/watch?v=8BNdxFzMeVg。 如果兴趣请自行翻墙观看
网友评论