无法在卸载的组件上调用setState(或forceUpdate)。应对

问题描述 投票:1回答:1

Gutentag,伙计们!

卸载组件后,我不断从我的应用程序收到此错误消息:

Warning: Can't call setState (or forceUpdate) 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.
    in Header (at index.js:27)

现在这里是Header组件的代码:

class Header extends Component {
  isCancelled = false;
  state = {
    someStateVars: x,
    separateColumns: 'true',
  }

  handleChange = (event) => {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    if (!this.isCancelled) {
      this.setState({ //######THIS IS LINE 27######
        [name]: value
      });
    }
  }

  handleDisplayChange = (event) => {
    const value = event.target.value;
    const name = 'separateColumns';

    if (!this.isCancelled) {
      this.setState({  
        [name]: value
      }, () => {
        this.props.displayChange();
      });
    }
  }

  serversRefresh = () => {

    if (!this.isCancelled) {
      setTimeout(() => {
        this.setState({refreshed: false});
      }, localStorage.getItem('seconds')*1000); //disable refresh for 15 seconds
    }
  }

  reactivateButton = () => {
    if (!this.isCancelled) this.setState({refreshed: false});
  }

  componentDidMount() {
    if(localStorage.getItem('seconds')>5 && !this.isCancelled){
      this.setState({refreshed: true});
    }
  }

  componentWillUnmount() {
    this.isCancelled = true;
  }
}

当我看到我收到此错误时,我添加了isCancelled变量,该变量在componentWillUnmount()函数中更改为true。

卸载Header组件后,15秒后,当serversRefreshbutton重新激活时,我收到此错误消息。

我该如何解决?

在我遇到此问题的另一个组件“isCancelled”var确实有帮助,但在这里我看到它没有影响,问题仍然存在。

javascript reactjs
1个回答
4
投票

只需将超时存储在变量中,例如

this.timeout = setTimeout(/* your actions here*/, /* your timeout */)

然后在componentWillUnmount中清除你的超时

componentWillUnmount() {
    clearTimeout(this.timeout)
}

它应该解决你的问题没有像this.isCancelled这样的拐杖。检测组件的安装状态是无操作的,因为即使在卸载后它仍然从内存中卸载。

setTimeout返回计时器的id,以后可以取消它。如果尚未执行,clearTimeout会通过它的id取消超时。

更多关于你的案例你可以在这里阅读:Why isMounted is antipattern

更多关于MDN的计时器。

© www.soinside.com 2019 - 2024. All rights reserved.