React Warning, Setstate(...) In Componentdidmount
Solution 1:
The FileUploaded
event handler is invoking setState
using a closure self
reference. This causes leaks where the component has been unmounted and then the FileUploaded
event triggers and setState is invoked on an unmounted component. You can read more about this in this article which is somewhat related - https://facebook.github.io/react/blog/2015/12/16/ismounted-antipattern.html.
Now how to fix this depends on if your uploader
object allows for unbinding the event handler. If it allows, then you can do this -
- Define the
FileUploaded
handler code as a named function (instead of anonymous). You need to do this to be able to unbind it later. - Change the code in
componentDidMount
to bind the named function as theFileUploaded
event handler. - Add a
componentWillUnmount
event handler to your component and call the unbind mechanism ofuploader
, passing it the named handler reference.
This way, when the component gets unmounted, the corresponding handler will also be removed and this warning will no longer be reported.
PS: You should remove (unbind) all handlers you are registering in your code above, otherwise you will be leaking references all over the place and more importantly, will be left with a whole bulk of orphaned event handlers.
==UPDATE==
Per your Fiddle, you can -
Declare these new methods in your component -
registerHandler: function(uploader, event, handler){ this.handlers = this.handlers || []; this.handlers.push({e: event, h: handler}); uploader.bind(event, handler); }, unregisterAllHandlers : function(uploader){ for (var i = 0; i < this.handlers.length; i++){ var handler = this.handlers[i], e = handler.e, h = handler.h; // REPLACE with the actual event unbinding method// of uploader. uploader.unbind(e, h); delete this.handlers[i]; } }, componentWillUnmount: function(){ this.unregisterAllHandlers(this.uploader); }
Use
registerHandler
in all the places where you are invokinguploader.bind
-self.registerHandler(self.uploader, event, handler);
OR
this.registerHandler(this.uploader,'FilesAdded', function (up, files) { if (_.get(self.props, 'multi_selection') === false) {...});
This is a very crude implementation, basically we are storing all event handler references in an array and then during unmount, removing them.
Post a Comment for "React Warning, Setstate(...) In Componentdidmount"