Cleanup memory leaks on an Unmounted Component in React Hooks

前端 未结 4 1383
再見小時候
再見小時候 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条回答
  •  生来不讨喜
    2020-12-13 10:03

    I know I'm a bit late, but there's a much simpler solution. Design your code to not use states after it gets unmounted.

    The warning arises when the component gets unmounted and you call setState which you did in

          .then(() => {
              setLoading(false); // Warning : memory leaks during the state update on the unmounted component <--------
           }) 
    

    Which you don't really need because this then happens iff the component is already unmounted. So you will not get the warning if you simply removed it.

    So my suggestion to anyone reading this now, try to refactor the code to not set states after calling a function that unmounts the component.

提交回复
热议问题