react icon indicating copy to clipboard operation
react copied to clipboard

setState can only update a mounted component warning

Open timurtu opened this issue 9 years ago • 7 comments

I'm getting the following warning in the console

screen shot 2017-03-13 at 8 16 36 pm

Here's the Snippet component causing the warning. I'm setting state in componentDidMount.

screen shot 2017-03-13 at 8 20 13 pm

I tried making a jsfiddle but there's too many dependencies. The error logged will increment on resize but it doesn't always happen.

timurtu avatar Mar 14 '17 00:03 timurtu

Could be because checkClearFix is being called when a resize occurs and the component is not mounted in the DOM?

milesj avatar Mar 14 '17 00:03 milesj

Hmm I just thought of that and removed it on componentWillUnmount

componentWillUnmount() {
    if (!this.props.splitTheGrid) {
      window.removeEventListener('resize', false)
    }
  }

but it's still happening

timurtu avatar Mar 14 '17 00:03 timurtu

@timurtu you have to pass the listener to removeEventListener, just like you do with addEventListener. You should just bind checkClearFix in the constructor and pass it directly to addEventListener instead of wrapping it in an arrow function that just calls it. Then you could pass this.checkClearFix to both addEventListener and removeEventListener

aweary avatar Mar 14 '17 01:03 aweary

Oh okay. Like this? It now says setState is not a function.

screen shot 2017-03-13 at 9 18 46 pm

timurtu avatar Mar 14 '17 01:03 timurtu

I also tried binding it here and now it gives the error from before

screen shot 2017-03-13 at 9 37 20 pm

timurtu avatar Mar 14 '17 01:03 timurtu

You would need to set the bind: this.checkClearFix = this.checkClearFix.bind(this);.

milesj avatar Mar 14 '17 05:03 milesj

that worked ty

timurtu avatar Mar 14 '17 05:03 timurtu