componentDidMount 总是会在 componentWillUnmount 之前被调用吗?

Stu*_*kel 5 reactjs

是否保证componentDidMount生命周期方法始终会在 之前执行(并完成)componentWillUnmount

例如,在我的componentDidMount方法中,我正在注册订阅:

componentDidMount() {
    this.unsubscribe = subscribe();
}

componentWillUnmount() {
    this.unsubscribe();
}
Run Code Online (Sandbox Code Playgroud)

如果componentDidMount不能保证componentWillUnmount在此之前执行并完成,则this.unsubscribe可能undefined会尝试调用它将引发运行时错误。

Kas*_*kas -1

关于生命周期方法的 React 类组件文档componentDidMount( https://reactjs.org/docs/react-component.html#componentdidmount ) 指出:

\n

This is a good place to set up any subscriptions. If you do that, don\xe2\x80\x99t forget to unsubscribe in componentWillUnmount().

\n

基于此,我想说保证总是componentDidMount会在之前执行componentWillUnmount,否则大多数取消订阅都会抛出您提到的错误。

\n