isMounted is not enough to know if you can setState
For the sake of this, I will simplify the workflow into three stages:
- The component is mounting, you may call setState, isMounted is false
- The component is mounted, you may call setState, isMounted is true
- The component is unmounted, you must not call setState, isMounted is false
The particular case I'm worried about is when you trigger a promise (or similar delayed action) from componentWillMount:
componentWillMount: function () {
doSomething(props).then(function (url) {
if (this.isMounted()) {
this.setState({url: url});
}
}.bind(this));
}
The .then() could be called in two circumstances, synchronously in the same call stack, or asynchronously in a later stack (I know, mixing async and sync in the same signature is a bad idea, but for the sake of argument).
In the asynchronous case: the promise above could resolve at any time in the future, so in order to prevent calling setState when we aren't allowed to, we add the isMounted() check. But what if the promise resolves while the component is still in the mounting state, outside of the componentWillMount stack?
- is it possible for this to happen? Is there a chance for other JS to run between componentWillMount and the component being mounted, or are they in the same cycle?
- if it can, what will happen? Will an error be shown?
In the synchronous case: we will enter the block still in the mounting state, which means isMounted() will be false and my state won't be set.
Depending on the answers to my async questions I can see two outcomes:
- Async cannot return before the component is mounted: this is a minor inconvenience that can be solved by coding such that you know what's async and what's not.
- Async can return before being mounted: there is no way to know if
setState()is safe to call or not, asisMounted()is incomplete. The user has to manually track the state of the component and if it has been unmounted or not.
Thoughts? Have I invented an issue where none exists?
Just to add to the confusion:
in componentWillUnmount, isMounted() is true and you are not allowed to setState()
+1 not to the original issue by to @dmitrig01's comment.
We explicitly say in the documentation that the goal of isMounted is to guard against setState:
http://facebook.github.io/react/docs/component-api.html#ismounted
So it's not right that it doesn't work in all cases
Can I question the point of isMounted? It just adds a lot of boilerplate. Is it possible to just build the check into setState? Unless the call to isMounted is expensive, I don't see any advantage to making the developer explicitly check it all the time.
function setState(newState) {
if(this.isMounted()) {
// insert setState code
}
}
Or, a setStateSafe, which does just that?
Yeah, isMounted check before setState is rather tedious IMO. I'd rather have setState returning boolean (false if it couldn't).
+1 setStateSafe. However, since I would always use setStateSafe and would see no use for setState, then I'm not sure we need setState at all, so why not replace the function entirely?
Either way, setStateSafe will only work if we fix the isMounted during componentWillUnmount issue.
I imagine setStateSafe would use some internal logic to determine what's safe or not, rather than using isMounted. It could even just fail silently rather than throwing an error like it currently does.
There might be a use case for an unsafe setState, but I can't think of one - it's certainly the more unlikely case.
I think in general, React has a pattern of blowing up in your face when you use it wrong (case in point, setState when a component is not mounted, but there are plenty of others) – which is in general good.
However, in some cases, if you know what you're doing, it would be nice to suppress these errors.
I would see the distinction as being - setState is used where the component is known to be mounted (which is probably most: e.g., onChange handlers of <input>, etc). setStateSafe is for asynchronous callbacks: timer, AJAX call, etc.
@sbrandwoo My understanding is that you're supposed to use componentWillUnmount to clean up any timers, cancel async requests, etc. Failure to cleanup is often a code smell that indicates a memory leak or other even more severe bug. That said, in the case of an asynchronous callback, it's easy to imagine why it would be easier to just ignore the update rather than attempt to cancel the callback, and this is where isMounted could come in as a handy guard.
Once a component is unmounted, I think it is effectively dead. I don't think it can be re-mounted (at least until opaque prerendered components are supported). There really shouldn't be a reason to update it anymore, so doing so would strongly imply a bug.
Having said that, I don't see why you couldn't set the state on an unmounted component, and the expected behavior is that it would effectively be a noop. My intuition would be to remove this error check and make setState and forceUpdate be valid at any time, maybe be a warning if you have findbugs turned on.
I suspect @sebmarkbage has strong opinions on this topic.
@jsfb to provide a concrete example of my use case, I have a "timer" component which counts down from 30 seconds to 0. I have one method to create an interval, and another to clear the interval. I call the method to clear the interval after the 30th tick and on componentWillUnmount. In the first case, I want to do a setState({ interval: null }), but in the second, I can't. There's no way that I know of to know whether it's safe to do that from within the method, without passing a parameter in.
In setState and replaceState are more checks than isMounted(), see function validateLifeCycleOnReplaceState(instance) in ReactCompositeComponent.js
I wrote a mixin, but due to limited access to internals, I am not happy with the result: http://github.com/rickbeerendonk/react-mixin-safe-state-change
Yea, there's no reason for this error to exist other than enforcing that you properly clean up your components. We could just as well ignore the value. I think that we'll likely make this a warning or at least make sure that it doesn't break reconciliation if it throws.
I would like to deprecate isMounted(). It's only really used as an escape to by-pass this error. The error is there to help you. If the easiest way to avoid the error is to add this isMounted() check, then it circumvents the whole purpose of having the error in the first place. You're not fixing the root problem. And as we all know, we tend to take shortcuts whenever we can. In practice, these go unfixed.
There are three separate scenarios in play here:
- Sometimes asynchronously and some times synchronously calling some method that might set state.
This is generally a really bad idea. This is a race condition that will act differently depending on the timing of your system, so testing won't reveal scenarios that an end user will hit. If you write in a completely immutable style, it's not as bad, but still considered bad practice.
If you have cached values, that you would like to use instead of causing two renders, you can at least build a separate synchronous API for that. E.g. in getInitialState: if (promise.hasCachedValue) return { value: promise.cachedValue }; It's better than violating the expectations of a Promise or async callback.
Additionally, in the current server rendering model, it's best practice to trigger async side-effects in componentDidMount since that will only fire on the client.
However, this is mostly a non-issue if (3) is solved since setState is currently still allowed in componentWillMount.
- setState in componentWillUnmount as a way to unify resetting values and clearing asynchronous callbacks.
This pattern seems a bit unnecessary to me. Unmounting and and reaching completion is two different concepts and are usually different code paths. Even if they do the same thing, it might be worth separating them to make refactoring easier when one changes.
I don't see this as a major issue that we even need to error in production, we could warn in dev. It doesn't suffer from the same consequences as (3). So we could even drop the warning.
However, the question is: Is it more commonly an mistake or a legit pattern? If it's a legit pattern, then we should not warn since warnings are meant to be cleaned up. Excessive warnings creates apathy. However, even if it is legit, should we warn anyway because the majority case is a mistake? I'm not sure. I could go either way. I don't think that this is a common mistake but not sure.
- Calling setState when a component is completely unmounted.
This is a strong indication that an asynchronous callback isn't being properly cleaned up. Unfortunately, mainstream JS APIs makes it very easy to avoid cleaning up hanging asynchronous callbacks.
One callback isn't a big deal. However, that callback hangs on to objects and intermediate callbacks, promises and subscriptions. If alot of your components do this, you will quickly run into memory issues.
This is a case of death by a thousand cuts. There is always a reason to avoid the complexity of cleanup logic, so you end up convincing yourself that it's ok for your special case. Then you run into GC and memory issues, and blame React for being slow. This is especially critical on mobile devices where memory issues can cause a browser to crash.
There are two types of callbacks. Infinite (or very long living) callbacks, such as event handlers that fire multiple times. There are also single fire callbacks such as Promises.
Promises are not as bad since they only resolve once before they can be cleaned up. However, they also live a long time. E.g. data requests can sometimes have very long timeouts to handle low-latency/bandwidth environments. The example above of a 30 second timeout is also an example of a long living promise. If your components frequently unmount and remount, you'll accumulate a lot of hanging promises and finally crash.
Therefore, it really bothers me that the JS community has adopted Promises at scale since it doesn't come with a cleanup mechanism. However, from a pragmatic point of view, we should probably allow this pattern to work since Promises are so common and make it very difficult to do clean up. You've been warned.
The big issue is that we can't really tell if the callback is coming from a Promise or a long living event. Failure to cleanup a long living event is a very common and dangerous mistake. So, how do we prevent that mistake from happening?
Even if the current callstack is coming from a Promise, that's no guarantee. That Promise could've fired a persistent event subscription that called setState. E.g. a Flux store.
Ultimately, I think that the solution is to build support for Promises in state. That way we can easily make an exception and ignore the warning if the Promise resolves late.
We should also build in support for Observables that make it easy to get cleanup for free.
We could easily ignore these setState calls but we'd need another way to ensure that you're not making common dangerous mistakes.
@sebmarkbage thanks for these points. But I think that you position React as a police to enforcing good practices (in your subjective opinion) by blowing up an app with throwing hard errors. IMO warning would be good enough. Thank you for consideration.
@shubik React already fails pretty softly in a bunch of places that I believe should be fatal. It's a complicated balance of making it abundantly clear to a developer exactly when/where things go wrong, vs. failing quietly. I agree with @sebmarkbage that we need a way to ensure developers are not making common dangerous mistakes, and provide escape hatches (like isMounted) when developers know what they're doing. That said, my intuition would be that setting state on an unmounted component would be analogous to a noop, so I tend to favor removing this error.
@jsfb I completely agree that ideally you would ignore setState on unmounted component and (at a given log level) print a respective warning. I would expect a hard error when your library has an internal error situation, not when it's an expected (although not desirable in your opinion) use case.
We'll probably make this a warning. However, note that we treat React warnings as if they're errors, except with a different code path in the error case. I.e. you should strive to never have any warnings in your code base. Even with a warning, it's not a fully supported use case and risk breaking.
I would like to be able to fully support the use case, but what's the API? I don't know. How do we distinguish between the clearly bad case (hanging callback) and a valid (in your opinion) pattern?
@sebmarkbage async XHR is a bad case but also the most common case, probably more common than timeouts or intervals that some of the commenters talked about - but at the other hand, as I and others pointed out, we are forced to check isMounted before every setState to make sure React never errors out. As I said, my main argument is that it makes more sense to throw an error if it's an internal error of React (e.g. using wrong arguments on React methods, etc.), not because of executing an async callback.
In any case, thanks a lot for your time and for having a dialog with us about this.
A common case for me is non-React (e.g. window.addEventListener) event handlers. Although I unbind them in componentWillUnmount, some of them still seem to come through and calling setState fails there without isMounted guard.
@gaearon that sounds like a bug either in your code or in React? Do you have a case that you're able to reproduce that we can take a look at?