Timeline for answer to Can't perform a React state update on an unmounted component by vinod
Current License: CC BY-SA 4.0
Post Revisions
9 events
| when toggle format | what | by | license | comment | |
|---|---|---|---|---|---|
| Jun 1, 2021 at 13:13 | comment | added | Mordechai | You won't get this warning of the variable is declared locally in the useEffect and an empty dependency array. | |
| Jun 1, 2021 at 6:50 | comment | added | havish | @Mordechai I believe it was done to avoid following warning from compiler: ``` Assignments to the 'isMounted' variable from inside React Hook useEffect will be lost after each render. To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property. Otherwise, you can move this variable directly inside useEffect ``` | |
| Jan 27, 2021 at 9:16 | comment | added | Stefan Becker |
If you use Babel and have enabled experimental JavaScript proposals then you can use a private class field for the flag, i.e. this.#isMounted
|
|
| Oct 15, 2020 at 22:35 | comment | added | Lightfire228 |
@Abhinav My best guess why this works is that _isMounted isn't managed by React (unlike state) and is therefore not subject to React's rendering pipeline. The issue is that when a component is set to be unmounted, React dequeues any calls to setState() (which would trigger a 're-render'); therefore, the state is never updated
|
|
| Jun 15, 2020 at 21:25 | comment | added | Mordechai | @x-magix You don't really need a ref for this, you can just use a local variable which the return function can close on. | |
| May 22, 2020 at 13:37 | comment | added | x-magix |
for hook component use this: const isMountedComponent = useRef(true); useEffect(() => { if (isMountedComponent.current) { ... } return () => { isMountedComponent.current = false; }; });
|
|
| Mar 2, 2020 at 10:51 | comment | added | Abhishek | It work fine. It stops the repetitive call of setState method because it validate _isMounted value before setState call, then at last again reset to false in componentWillUnmount(). I think, that's the way it work. | |
| Feb 22, 2020 at 19:55 | comment | added | Abhinav | This worked, but why should this work? What exactly causes this error? and how this fixed it :| | |
| Jun 11, 2019 at 6:25 | history | answered | vinod | CC BY-SA 4.0 |