D
D
Dmitry Markov2021-09-20 15:20:05
React
Dmitry Markov, 2021-09-20 15:20:05

How to unmount what is not in useEffect?

I have an observer in my component to load content. It turns out when the observer is triggered, there is a request to the server (asynchronous garbage). If I switch from one route to another and switch back, I get the 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. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function". I found out that this error is caused by a state change in the rest response and so I think that I need to unmount it, but I can only unmount what is in useEffect, and my setstates are not in it)
Question.
How to unmount it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2021-09-20
@Alexandroppolus

The problem is that you are launching asynchronous actions in useEffect. This is not very correct, it is better to take out the logic separately, and add its results to the stack.
If you need to fix it very quickly without refactoring, then you can add an unmount check so as not to change the state of the unmounted component.

const useCheckMounted = (): (() => boolean) => {
  const ref = useRef(true)
  useLayoutEffect(() => {
    ref.current = true
    return () => {
      ref.current = false
    }
  }, [ref])
  return useCallback(() => {
    return ref.current
  }, [ref])
}

// пример использования:
const Child: React.FC = React.memo(() => {
  const check = useCheckMounted()

  useEffect(() => {
    console.log('check1, ', check())
    setTimeout(() => {
      console.log('check2, ', check())
    }, 8000)
  }, [check])

  return <div>child</div>
})

this component fires a setTimeout symbolizing a long request. Before running check() returns true - the component is mounted. When the server responds, check() will return false if the component has crashed, or true if it is still alive.
An example on TS, if anything - just remove the types

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question