React-防止内存泄漏处理

1,151 阅读1分钟
报错信息

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组件已经被销毁,而此时我们的异步操作(通常为调用接口更改state操作)还未结束。当我们的异步执行完成后要执行setState操作时,已经无法获得组件信息,由此造成该异常!

解决方案

1、我们应该在组件中通过componentWillUnmount钩子函数在组件销毁的时候将异步方法撤销:

componentWillUnmount() {
    this.setState = ()=>false;
}

2、使用标记_isMounted记录页面销毁

constructor(props) {
    super(props);
    this._isMounted = false; 
}

componentDidMount() {
   this._isMounted = true;
   this._isMounted && fetch(`http://localhost:8000/albums`)
   .then((response) =>
      response.json())
   .then((data) => {
      this.setState({ album : data });
    }).catch((error) => {
        console.log("Error " + error)
    })
}

componentDidUpdate() {
   this._isMounted && fetch(`http://localhost:8000/albums`)
   .then((response) =>
      response.json())
   .then((data) => {
      this.setState({ album : data });
   }).catch((error) => {
      console.log("Error " + error)
   })