Cleaning function in useEffect is not working

Asked

Viewed 199 times

0

Hello! I am trying to cancel my api call using Axios when the component is unmounted, and although it seems to be being canceled, I still 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 %s. %s, a useEffect Cleanup Function.

I’m trying to clean up this way:

  useEffect(() => {
    const source = axios.CancelToken.source();

    if(requestLoading){
      async function addNewUser() {
        await api.post('/api/Auth/register', {
          name,
          email,
          password
        },{
          cancelToken: source.token
        }).then(response => {
          const statusCode = response.status
          setRequestLoading(false)
          if (statusCode == 201) {
            navigation.navigate('home')
          }

        }).catch(error => {
          setRequestLoading(false)

          if(axios.isCancel(error)) {
            console.log('Request canceled')
          } else {
            setModalVisible(true)
            setApiMessage(error.response.data.errors)
            setTimeout(() => {
                setModalVisible(false)
            }, 3000)
            Vibration.vibrate(500)
          }
        }) 
      }
      addNewUser()

//FUNÇÃO DE LIMPEZA
      return () => {
        console.log('unmounting')
        setRequestLoading(false)
        source.cancel()
      }
    }
  }, [requestLoading])

If anyone can help me find where I’m going wrong, I really appreciate it because I’m new to developing with React Native!

  • I don’t know if that’s all it is, but when you set up the array that useEffects to observe a certain variable and in the middle of the code has the same update of this variable ( setRequestLoading(false) ) he calls again and creates a loop ... must be that first of all.

  • This was really wrong and I performed the correction by removing all the setRequestLoading(false) from within the useEffect(). However, the error still occurs when unmounting the component. Thank you!

  • You have to analyze all the mistakes, and almost impossible for us to guess if you can edit your question and clarify better

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.