markusenglund / react-switch

A draggable toggle-switch component for React. Check out the demo at:
https://react-switch.netlify.com/
MIT License
1.33k stars 101 forks source link

Prevent setState when not mounted #87

Closed smhg closed 3 years ago

smhg commented 3 years ago

When react-switch runs an onChange callback which unmounts the component (e.g. conditional render on toggle inside the parent component), a React warning appears:

Can't perform a React state update 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.

This is caused by this.setState being called after an onChange which caused an unmount. This PR adds mount/unmount tracking and prevents those setState that would run after unmount.

smhg commented 3 years ago

That's a good catch. I've removed the default property value in the constructor.

markusenglund commented 3 years ago

Cool. Alright, I'm merging it in to the 6.0.0 branch. The plan is to get the release out sometime during the christmas break.