1

Recently I came across the issue of fetch() and setState() return to an unmounted component, resulting in an error. I am looking for a simple solution that does not involve redux or cancelling fetch().

A partial solution might be to use a local variable this._isMounted that is set to true at componentDidMount and false at componentWillUnMount

Now, if you perform:

if (this._isMounted) setState({whatever})

This is almost complete. The hole is the period of time, after the condition check and until setState() completes. Is there a way, by means of semaphores to handle this issue.

For example, delay componentWillUnmount access to this._isMounted, by waiting for setState() semaphore?

Delay may sound bad and not be appropriate in some cases, but semaphores and legacy operating systems solution do seem relevant where async operations take place IMO.

Mulli
  • 1,598
  • 2
  • 22
  • 39
  • "I came across the issue of fetch() and setState() return to an unmounted component, resulting in an error." Can you share more about your component and the error? – jmargolisvt Nov 27 '18 at 03:59
  • I am referring to a general issue, please look at https://stackoverflow.com/questions/49906437/how-to-cancel-a-fetch-on-componentwillunmount – Mulli Nov 27 '18 at 04:02
  • "The hole is the period of time, after the condition check and until setState() completes." There's no opportunity for anything to happen between the test and setState(). There's a single JavaScript thread. – Joshua R. Nov 27 '18 at 04:08
  • Single but handles async. calls, please look at https://medium.com/@wereHamster/beware-react-setstate-is-asynchronous-ce87ef1a9cf3 So at that time, until setState() completes & returns, the user can move away from the component, resulting in an unmount prior to setState completion – Mulli Nov 27 '18 at 04:13
  • 1
    If you are looking for a JavaScript semphore, check out [Semaphores in JavaScript](https://medium.com/swlh/semaphores-in-javascript-e415b0d684bc) – Tom Aranda Aug 22 '22 at 20:32

0 Answers0