在包裹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
是我需要用来卸载组件的东西,但是我要卸载的是setState
或firebase.auth.onAuthStateChanged
?
答案 0 :(得分:5)
问题在于,当您卸载组件时,firebase事件onAuthStateChanged
仍将调用。如果在删除(卸载)组件后确实调用了该命令,则会出现错误。
为了解决此问题,您需要取消componentWillUnmount()
中的事件订阅。您可以通过调用从订户返回的函数来执行此操作。例如:
componentDidMount() {
this.cancelSubscription = firebase.auth.onAuthStateChanged ...
}
componentWillUnmount() {
this.cancelSubscription()
}