Warning: setState(...): Can only update a mounted or mounting component. This usually means you call

前端之家收集整理的这篇文章主要介绍了Warning: setState(...): Can only update a mounted or mounting component. This usually means you call前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

类似这个错误

出现这个错误,大部分是因为使用了fetch获取数据,并在then中调用了setState()

  1. class Overall extends Component {
  2.  
  3. componentDidMount() {
  4. this.fetchData();
  5. }
  6.  
  7. fetchData(){
  8. fetch(url).then(() => {
  9. this.setState({...}); // 获取 返回数据
  10. })
  11. }
  12.  
  13. ....
  14. }

如果@H_502_26@Overall 组件unmount 后才获取返回数据,那么此时该组件已经unmounted,调用this.setState() 会弹出警告

我们应该避免,在已经unmounted component中调用 setState(),同时,需要思考为什么我们需要调用setState(),如果在unmounted中调用setState,意味着程序仍然保留这个组件的引用,会浪费内存。如果有必要,我们应该把这些数据存在store中。

另一种思路,取消fetch请求。

解决方法
https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html

猜你在找的React相关文章