react组件销毁中清理异步操作和取消请求

2020-07-24阅读(3752)评论(0)牵着狗狗看MM

苏州实时公交查询

react报错信息:
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.

原因:

通常是 react 组件已经从 DOM 中移除,但是我们在组件中做的一些异步操作还未结束,如:接口调用等,当其完成时,执行setState操作,而此时我们已经将改组件dom移除,从而导致上述问题。

解决方法:

componentWillUnmount() {
        // 卸载异步操作设置状态
        this.setState = () => {}
    }

 

赞(6)
转载请注明来源:Web前端(W3Cways.com) - Web前端学习之路 » react组件销毁中清理异步操作和取消请求
分享到: 更多 (0)