React-hooks. Can't perform a React state update on an unmounted component

前端 未结 3 2033
孤独总比滥情好
孤独总比滥情好 2020-12-01 02:11

I get this error:

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

3条回答
  •  一整个雨季
    2020-12-01 02:39

    TL;DR

    Here is a CodeSandBox example

    The other answers work of course, I just wanted to share a solution I came up with. I built this hook that works just like React's useState, but will only setState if the component is mounted. I find it more elegant because you don't have to mess arround with an isMounted variable in your component !

    Installation :

    npm install use-state-if-mounted
    

    Usage :

    const [count, setCount] = useStateIfMounted(0);
    

    You can find more advanced documentation on the npm page of the hook.

提交回复
热议问题