I am using Socket.io Callbacks with react. However, sometimes I get this warning
Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
Fundamentally, I understand that the callback can be holding references to local data and preventing that data from being cleared until the callback is cleared.
Unfortunately Socket.io does not work with promises but with direct callbacks. What this means is that I may get a callback AFTER the component has unmounted since these callbacks cannot be "cancelled"
I make sure that the server responds to all callbacks to make sure they get satisfied and therefore do not leak memory
I attempted to "silence" this warning by calling this.setState({mounted:true});
in componentDidMount
and this.setState({mounted:false});
in componentWillUnmount
And then within my update simply checking if(this.state.mounted)
before calling this.setState()
within the socket.io callback.
This works for most cases. However it seems that in this case. The parent component causes this component
- componentDidMount
- update state to mounted:true
- send request to socket.io -componentWillUnmount
- update state to mounted:false
- componentDidMount
- update state to mounted:true
- send additional request to socket.io
- Callback response from socket.io
- warning printed
How do I prevent this? Is there a better design pattern for sock.io