You are mixing a couple of things in your code. You are using await but not calling await when you use this.showPosts()
. You are also not wrapping your await
in a try/catch
as await
can throw.
There a couple of ways that you can solve the problem of setting state on an unmounted component. The most simplest, though it is an anti-pattern is to do is to set a variable in the componentDidMount
and the componentWillUnmount
that tracks the mounted state of the component.
So let's refactor your code so that it makes more sense
This is how your componentDidMount
and the componentWillUnmount
will now look.
async componentDidMount () {
this._isMounted = true;
await this.showPosts();
}
componentWillUnmount () {
this._isMounted = false;
}
Updating showPosts
so that it is purely async/await
showPosts = async () => {
try {
var userID = await AsyncStorage.getItem('userID');
let response = await fetch(strings.baseUri + 'getPostWithUserID', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
'user_id': userID
})
});
let responseJson = await response.json();
if (this._isMounted) {
this.setState({show: false});
}
} catch (err) {
console.error(error);
}
}
Or if we use your current implementation of showPosts it would look like this, but fixing the lack of try/catch around the await.
showPosts = async () => {
try {
var userID = await AsyncStorage.getItem('userID');
fetch(strings.baseUri + 'getPostWithUserID', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
'user_id': userID
})
})
.then((response) => response.json())
.then((responseJson) => {
if (this._isMounted) {
this.setState({show: false}); // If I comment this line, then I don't get the warning.
}
})
.catch((error) => {
console.error(error);
});
} catch (err) {
console.warn(err);
}
}
An alternative is to get into cancelling promises once they have been made. This article goes someway to explaining how to do it https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html