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
thatuseEffects
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 aloop
... must be that first of all.– novic
This was really wrong and I performed the correction by removing all the
setRequestLoading(false)
from within theuseEffect()
. However, the error still occurs when unmounting the component. Thank you!– Renato
You have to analyze all the mistakes, and almost impossible for us to guess if you can edit your question and clarify better
– novic