React warning about setState in unmounted component

后端 未结 2 1200
终归单人心
终归单人心 2020-12-08 13:38

I\'m getting this error:

warning.js:33 Warning: Can\'t call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates

2条回答
  •  遥遥无期
    2020-12-08 14:00

    I had a similar problem, but I did figure out the reason behind the same, so here is the snippet of code where I was encountering this err.

    Warning: 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.
    
    

    Cause:

       this.setState({ showLoader: true });
        const { username } = this.state;
        const URL = `https://api.github.com/users/${username}`;
        try {
          const { data } = await axios(URL);
          this.props.apiData(data);
          this.props.history.push("profile");
        } catch (e) {
          console.error(e);
        }
        this.setState({ showLoader: false });
    

    As you can see in the code-snippet, I was doing

    this.props.history.push("profile");
    

    before setting the state.

    this.setState({ showLoader: false });
    

    And then err seems to be legit in this case as I was redirecting to a different component and then setting the state on the component I was earlier.

    Solution:

    By placing

    this.setState({ showLoader: false });
    

    above the this.props.history.push("profile"); solved the problem.

    I hope this helps.

提交回复
热议问题