0

lets assume something lile this:

handleClick = () => {
  dispatchThunkAction(this.someMethod),
}

someMethod = () => {
  //do something
}

dispatchThunkAction fires http request. once done, thunk action calls back someMethod thats passed to it.

should someMethod be set to null in componentWiUnmount for the case unmount happens in the middle of http (or any other async operation) call?

so, like

componentWillUnmount() {
  this.someMethod = null;
}

so that garbage collector knows it can pick it up immediately.

dee zg
  • 10,582
  • 7
  • 33
  • 59

1 Answers1

2

Setting the method to null will not help, but you could create an instance variable called e.g. _isMounted that you set to false in componentDidUnmount and check that this variable is true before you do anything in someMethod.

class App extends React.Component {
  _isMounted = true

  handleClick = () => {
    dispatchThunkAction(this.someMethod)
  }

  someMethod = () => {
    if (!this._isMounted) {
      return
    }

    //do something
  }

  componentDidUnmount() {
    this._isMounted = false
  }  

  // ...
}
Tholle
  • 83,208
  • 13
  • 152
  • 148
  • so you are effectively saying that component cannot be really unmounted for as long as thunk action keeps reference to its method? if i understand correctly? (null-check before calling it on thunk action side is not my concern atm) – dee zg Feb 15 '19 at 17:55
  • @deezg The component will still be unmounted as usual even with the `_isMounted` instance variable, but you keep a value indicating that it has been unmounted. – Tholle Feb 15 '19 at 17:58
  • ok, so there are 2 different things here: unmounted (as react component state) and ready to be garbage collected. i guess what you are saying is it will be unmounted but not ready for garbage collection for as long as thunk action keeps reference to `someMethod`. is that correct statement? – dee zg Feb 15 '19 at 18:04
  • @deezg Yes, that's right. The garbage collection will resolve itself eventually, but not checking if the component is still mounted before using `setState` will result in a warning. – Tholle Feb 15 '19 at 18:07
  • 1
    right right, now it makes perfect sense. thanks for clarifications! – dee zg Feb 15 '19 at 18:08