美文网首页让前端飞
react: Warning: Can't perfor

react: Warning: Can't perfor

作者: EdmundChen | 来源:发表于2018-12-15 22:19 被阅读6次

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() , 通常有两种情况。

  1. 设置了定时器setinterval 或者递归setTimeout。 unmonut之前没有清除掉。
  2. 异步请求callback在请求回来之前组件已经unmount

解决办法

1. 对于定时器

componentWillUnmount 生命周期, 必须clear调用定时器

2.对于异步请求

两种解决方案。

  • 方案一 设置标志位在挂载是为true,componentWillUnmount 时设为false,然后在异步调用的callback里面做判断
  • 方案二componentWillUnmount 取消异步请求

一个老外的解说视频https://www.youtube.com/watch?v=8BNdxFzMeVg。 如果兴趣请自行翻墙观看

相关文章

网友评论

    本文标题:react: Warning: Can't perfor

    本文链接:https://www.haomeiwen.com/subject/wnrzhqtx.html