Can't call setState (or forceUpdate) on an unmounted component

时光毁灭记忆、已成空白 提交于 2019-12-02 20:29:09

A common pattern I use in this instance is something along the lines of

componentWillUnmount() {
    this.isCancelled = true;
}

And then in the code where you're awaiting an async function to resolve, you would add a check before setting state:

async componentDidUpdate(prevProps, prevState) {
    if (this.props.subject.length && prevProps.subject !== this.props.subject) {
        let result = await this.getGrades({
            student: this.props.id,
            subject: this.props.subject
        });
        !this.isCancelled && this.setState({
            subject: this.props.subject,
            grades: result
        });
    }
}

That will stop any state setting on unmounted/unmounting components

The accepted answer works, and is a valid workaround for the problem of calling asynchronous functions in the component rendering methods (getInitialState, componentWillMount, componentDidMount).

But a better practice would be to use state management helpers like Redux and Flux and a global store, this might avoid the problem of multiple setStates.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!