Keep getting the following error message in React Native, really don't understand where it is coming from
Warning: Can't call setState (or forceUpdate) 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 the componentWillUnmount method.
I have the following simple component:
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
isLoggedIn: false,
}
}
componentDidMount(){
this.fetchToken()
}
async fetchToken(){
const access_token = await AsyncStorage.getItem('access_token')
if (access_token !== null) {
this.setState({ isLoggedIn: true })
}
}
render() {
const login = this.state.isLoggedIn
if (login) {
return <NavigatorLoggedIn />
} else {
return <Navigator/>
}
}
}
this.state, not juststate. I also wouldn't apply theasyncattribute to React's default lifecycle methods, best leave them as they are. Create a separateasync/awaitcomponent function for doing that, then call it incomponentDidMount- Jayce444componentDidMount()runs after rendering so updated state is not seen/available inrender(). Then I suppose this component gets unmounted viarender()in any case and so callingfetchToken()after the fact causes a memory leak, per the error messgage. - radarbobrender()at the very top. (2) do it in the constructor. In either case use the other form ofsetState()that takes a function; becausesetState()is fundamentally asynchronous - radarbob