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

1、问题bug 1   

Fetch不能中断的话 那如何在组件移除之前 移除掉这个异步请求?

React中,因为异步操作的关系,组件销毁后调用了setState(),报警告,怎么解决?

 我在componetWillMount中访问了接口返回数据后,调用了setState,访问的时候按了后退,导致还没收到响应就销毁了组件 ,但是fetch请求没被结束掉,之后 收到响应就调用了setState(),发出警告。请问这种情况该怎么处理?在unmount中结束fetch吗?但fetch怎么结束呢?官方文档好像没有api

解决方法


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 = (state, callback) => {
            return;
        }
    }

  

猜你喜欢

转载自www.cnblogs.com/yuanjili666/p/11756278.html