Cleanup memory leaks on an Unmounted Component in React Hooks

前端 未结 4 1381
再見小時候
再見小時候 2020-12-13 09:06

I\'m new using React, so this might be really simple to achieve but I can\'t figure it out by myself even though I\'ve done some research. Forgive me if this is too dumb.

4条回答
  •  Happy的楠姐
    2020-12-13 09:47

    Before mutating the state, you should first check whether the component is still mounted.

    As said above by @SanjiMika, when having an async action that causes this error, it means you are trying to mutate the component's state after it was un-mounted.

    react-use provides hooks for that, you've got 2 options:

    option #1: useMountedState

    // check if isMounted before changing any state
    const isMounted = useMountedState();
    
    useEffect(() => {
      const asyncAction = executeAsyncAction();
    
      asyncAction.then(result => {
        if (isMounted) {
          // It's safe to mutate state here
        }
      });
    }, []);
    

    option #2: useUnmountPromise

    /* `resolveWhileMounted` wraps your promise, and returns a promise that will resolve 
     * only while the component is still mounted */
    const resolveWhileMounted = useUnmountPromise();
    
    useEffect(async () => {
      const asyncAction = executeAsyncAction();
    
      resolveWhileMounted(asyncAction).then(result => {
        // It's safe to mutate state here
      });
    }, []);
    
    

提交回复
热议问题