Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

186
Visualizações
useEffect cleanup on 'imported' async function

Please don't consider this a duplicate. I have searched many blogs and stuffs but haven't reached to the solution.

First of all, my question is 'how to resolve react state change in unmounted component error, and cancel an async function call that is imported within the useEffect hook?'

I know that you can resolve 'state changed in an unmounted component' error by using clean up function in useEffect. In the cases of async call within useEffect hook, you can do clearTimeout, use cancel token for Axios, create [isMounted] state to flag mounted/unmounted state, and etc. So, at least, I know how to veil the react warning

However, my boss wants not only veiling the warning but also cancelling the async request. Here's the simplified version of code.

import { fetchFunction } from '../../../somewhereInTheDir';

function Page() {
  const [data, setData] = useState([]);
  const [isMounted, setIsMounted] = useState(true);

  async function fetchData() {
    try {
      const data = await fetchFunction(someUri);

      setData(data);
    } catch (error) {
      console.warn(error);
    }
  }

  useEffect(() => {
    if(isMounted) {
      fetchData(ENDPOINT);
    }
    
    return () => {
      setIsMounted(false);
    }
  })
}

The isMounted state veils the warning. So I am seeing nothin in the console, which is a good sign. But this code does not block/cancel data coming from the endpoint when Page component is unmounted. And you cannot use strategies like putting cancel token in the http header, because fetchFunction is from outside.

ps. my boss said using isMounted state as if it were a JavaScript variable could be an anti-pattern from React, since React state change leads to a re-rendering. Is there a better way to veil the warning without using isMounted state?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can try this approach instead. Keep track of the mounted status in the hook itself, as well as the conditional setState function.

Also it is important that you include the empty dependency array, otherwise your component will call the hook on every render.

import { fetchFunction } from '../../../somewhereInTheDir';

function Page() {
  const [data, setData] = useState([]);
  const [isMounted, setIsMounted] = useState(true);

  async function fetchData() {
    try {
      return await fetchFunction(someUri);
    } catch (error) {
      console.warn(error);
    }
  }

useEffect(() => { // <- you can't change this to async
  let mounted = true

    // Variant with Promise
    fetchData(ENDPOINT).then(data => {
      if (mounted) setData(data);
    })

    // Variant with async/await
    (async () => {
      const data = await fetchData(ENDPOINT)
      if (mounted) setData(data);
    }())
    
    return () => {
      mounted = false
    }
  }, []) // <- empty dependency array is important here
}

The following article introduces few other methods how to handle the mounting state even if you use multiple useEffect hooks, etc.

https://www.benmvp.com/blog/handling-async-react-component-effects-after-unmount/

about 4 years ago · Juan Pablo Isaza Relatório

0

Regarding the last paragraph of your question, you can use refs instead of state.

const isMounted = useRef(false)

useEffect(() => {
    isMounted.current = true
    return () => isMounted.current=false
}, [])
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda