我要在componentDidMount中卸载什么

时间:2018-09-25 01:32:24

标签: javascript reactjs

在包裹component的页面中,我正在state中设置componentDidMount来处理logging身份验证为

componentDidMount() {
  if (typeof window !== 'undefined') {
    firebase.auth.onAuthStateChanged(authUser => {
      authUser
        ? this.setState(() => ({ authUser }))
        : this.setState(() => ({ authUser: null }));
    });
  }
}

但是,在某些页面渲染中,我收到此错误。

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.

很明显,componentWillUnmount是我需要用来卸载组件的东西,但是我要卸载的是setStatefirebase.auth.onAuthStateChanged

1 个答案:

答案 0 :(得分:5)

问题在于,当您卸载组件时,firebase事件onAuthStateChanged仍将调用。如果在删除(卸载)组件后确实调用了该命令,则会出现错误。

为了解决此问题,您需要取消componentWillUnmount()中的事件订阅。您可以通过调用从订户返回的函数来执行此操作。例如:

componentDidMount() {
  this.cancelSubscription = firebase.auth.onAuthStateChanged ...
}

componentWillUnmount() {
  this.cancelSubscription()
}