React setState pitfalls
You should use caution when using setState in an asynchronous context. For example, you might try to call setState in the callback of a get request:
This could call problems - if the callback is called after the Component is dismounted, then this.setState won't be a function. Whenever this is the case, you should be careful to ensure your usage of setState is cancellable.
In this example, you might wish to cancel the XHR request when the component dismounts:
The async method is saved as a state. In the componentWillUnmount you perform all your cleanup - including canceling the XHR request.
You could also do something more complex. In this example, I'm creating a 'stateSetter' function that accepts the this object as an argument and prevents this.setState when the function cancel has been called:
This works because the cancelled variable is visible in the setState closure we created.