加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Warning: setState(...): Can only update a mounted or mountin

发布时间:2020-12-15 06:32:06 所属栏目:百科 来源:网络整理
导读:类似这个错误 出现这个错误,大部分是因为使用了fetch获取数据,并在then中调用了setState() class Overall extends Component { componentDidMount() { this .fetchData(); } fetchData(){ fetch(url).then(() = { this .setState({...}); // 获取 返回数据

类似这个错误

出现这个错误,大部分是因为使用了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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读