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()

class Overall extends Component {

    componentDidMount() {
        this.fetchData();
    }

    fetchData(){
        fetch(url).then(() => {
            this.setState({...});    // 获取 返回数据
        })
    }

    ....
}

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

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

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

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

原文链接:https://www.f2er.com/react/301806.html

猜你在找的React相关文章