I just develop a SPA and need help with the asynchronous requests I send by react componentDidMount to my server side (node). The queries work, but if I change quickly to the different pages, the setState functions within the ajax response are still running. Although the components are unmounted.
Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component.
To avoid this error, I would like to abort/cancel the request which I send on componentWillUnmount if this is the correct way to do this.
I tried this with xml and with axios but it doesnt work. I hope you have a working example for me. Iam open for other request methods like fetch or something.
The code looks something like this (Axios), but it doesn't cancel the request:
import * as React from 'react';
import axios from 'axios';
let CancelToken = axios.CancelToken;
let source = CancelToken.source();
class MakeAjaxRequest extends React.Component {
constructor() {
super();
this.state = {
data: {}
}
}
componentDidMount() {
const that = this;
axios.get('/user/12345', {
cancelToken: source.token
})
.then(function (response) {
if (axios.isCancel(response)) {
console.log('Request canceled', response);
} else {
that.setState({
data: response.data
});
}
})
.catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
});
}
componentWillUnmount() {
source.cancel('Operation canceled by the user.');
}
//....other stuff, like render the data
}
Axios has the option of cancelling requests:
https://github.com/axios/axios#cancellation
Another way of preventing setState from firing on some kind of callback after the component is unmounted is to have a local boolean variable storing whether or not the component is mounted, i.e.
componentDidMount(){
this._mounted = true;
}
componentWillUnmount() {
this._mounted = false;
}
Then in the axios callback check whether _mounted
is true before trying to call setState()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With