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

前端 未结 2 463
不知归路
不知归路 2021-02-02 11:35

I\'m trying to fetch the data from the server after component has been updated but I couldn\'t manage to do that. As far as I understand componentWillUnmount is cal

相关标签:
2条回答
  • 2021-02-02 11:44

    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.

    0 讨论(0)
  • 2021-02-02 11:54

    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

    0 讨论(0)
提交回复
热议问题