0

how we can use setState in componentDidMount() or how we can change state value?. While using below code getting error

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

componentDidMount(){
  this.interval = setInterval(() => {
    if(this.state.rmSec==0){
      this.setState({
        rmSec:59,
        rmMin:this.state.rmMin-this.state.minus,
      })
    }else{
      this.setState({
        rmSec:this.state.rmSec-this.state.minus
      })
    }

    if(this.state.rmMin==0){
      this.setState({
        rmSec:0,
        rmMin:0,
      })

    }


  }, 1000);
}
Shibin Raju Mathew
  • 920
  • 4
  • 18
  • 41

2 Answers2

0

Checking isMounted before calling setState() does eliminate the warning, but it also defeats the purpose of the warning, since now you will never get the warning (even when you should!).The primary use case for isMounted() is to avoid calling setState() after a component has unmounted, because calling setState() after a component has unmounted will emit a warning. More here : https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html. So try like

 constructor(props) {
       this.state = {isMounted: false}
    }
 componentDidMount() {
       this.setState( { isMounted: true }, () => {

    });
}
componentWillUnmount() {
       this.setState( { isMounted: false } )
}

Warning: isMounted(...) is deprecated in plain Javascript Classes. Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks.Looks like an RN issue and it will get fixed soon i guess

Aravind S
  • 2,347
  • 2
  • 12
  • 21
  • componentDidMount(){ this.interval = setInterval(() => { if(this.state.rmSec==0){ this.setState( { isMounted: true }, () => { rmSec:59; rmMin:this.state.rmMin-this.state.minus; }); }else{ this.setState( { isMounted: true }, () => { rmSec:this.state.rmSec-this.state.minus; }); } if(this.state.rmMin==0){ this.setState({ rmSec:0, rmMin:0, }) } }, 1000); } – Shibin Raju Mathew Jul 26 '18 at 07:27
  • for the third setState, its missing. can you add the condition for that also and try once – Aravind S Jul 26 '18 at 08:16
  • Again Same issue... `componentDidMount(){ this.interval = setInterval(() => { if(this.state.rmSec==0){ this.setState( { isMounted: true }, () => { this.setState({ rmSec:59, rmMin:this.state.rmMin-this.state.minus, }); }) }else{ this.setState( { isMounted: true }, () => { this.setState({ rmSec:this.state.rmSec-this.state.minus, })})} if(this.state.rmMin==0){ this.setState( { isMounted: true }, () => { this.setState({ rmSec:0, rmMin:0, })} }}, 1000);}` – Shibin Raju Mathew Jul 26 '18 at 10:44
  • @ShibinRajuMathew That looks weird..can you stack trace which line is causing the error? – Aravind S Jul 26 '18 at 11:12
0

Issue solved by clearing interval on unmount

componentWillUnmount () {
    this.interval && clearInterval(this.interval);
    this.interval = false;
}
Shibin Raju Mathew
  • 920
  • 4
  • 18
  • 41