0

I have for a long while assumed that code I put inside the componentDidMount life cycle method gets called only if the component is mounted. But now I am being told that it might not be the case at all times. For instance, while I am fetching some data inside the componentDidMount method, a user could navigate to another component and cause my component to unmount. And when the data fetching is done, they tell me, the line of code after the data fetching continues naively executing as if the component is still mounted, and that causes some nasty error. Isn't it react's job to ensure that my code doesn't run when my component is unmounted, and resumes only when it is mounted?

  • Its because fetching data is an async task. The logic is like this: component mounted > calling async fetch > user changes view > meanwhile async fetch finishes and calls setState with new data > react trying to update state accordingly but can't find it anymore. React can't and shouldn't just cancel your promise. – oemera Nov 29 '19 at 20:16
  • Why cause an error upon calling `setState`? If my component is not in view why allow some async task to modify its state, shouldn't they detect that for me? – faint-hearted-fool Nov 29 '19 at 20:42

1 Answers1

2

UI-programming in general must be asynchronous, such that pressing button doesn't freeze the entire visuals. Therefor flexibility must be left in the framework, like not halting everything just to wait for lifecycle methods. This is the programmers job. API just promises that componentDidMount is called at certain point, nothing else.

If you anticipate long running process in componentDidMount, you could periodically check for instance if componentWillUnmount has been called and if so then cancel execution.

imiro
  • 167
  • 7
  • You are saying I have to check if `componentUnmount` is called, and then cancel the task. Why can't they do that for me? The know when `componentUnmount` is called, why can't they cancel the task (or ignore upcoming `setState` calls)? Why do I have to bother checking ... I mean who would be interested in updating the state of a component that is not in view? – faint-hearted-fool Nov 29 '19 at 20:47
  • 1
    React does destroy the component and there will be no more render() calls after component has unmounted. ComponentWillUnmount signals you that you can no longer be sure the component works as usual e.g. setState. Please see this discussion: https://stackoverflow.com/questions/39767482/is-there-a-way-to-check-if-the-react-component-is-unmounted . Worth noting that cancellable is the correct way to deal with middle-process unmounting. – imiro Nov 29 '19 at 21:21