Cancel All Subscriptions and Asyncs in the componentWillUnmount Method, how?

前端 未结 3 1513
鱼传尺愫
鱼传尺愫 2020-12-09 14:58

I\'m getting an error message due to an async method issue. In my terminal I\'m seeing:

Warning: Can\'t call setState (or forceUpdate) on an unmounted compon         


        
3条回答
  •  余生分开走
    2020-12-09 15:58

    You need to set this.mounted = false in componentWillUnmount() method and this.mounted = true in componentDidMount() method.

    The setState update is conditional based need to declare in componentDidMount() method.

    componentDidMount() {
            this.mounted = true;
            var myVar =  setInterval(() => {
                    let nextPercent = this.state.percentage+10;
                    if (nextPercent >= 100) {
                        clearInterval(myVar);
                    }
                    if(this.mounted) {
                        this.setState({ percentage: nextPercent });
                }
            }, 100);
    }
    
    componentWillUnmount(){
          this.mounted = false;
    }
    

提交回复
热议问题