简体   繁体   中英

Warning: Can't call setState (or forceUpdate) on an unmounted component in React Native

Full error image: error image

I am making a fetch request and when I want to set the state to save some errors that happens. How do I fix this?

Code:

    onClickLogIn = (username, password) => {
    const request = fetch('[SOMEAPILINK]', {
    method: 'POST',
    headers: {
        Accept: 'text/javascript',
        'Content-Type': 'text/javascript',
    },
    body: JSON.stringify({
        username: username,
        password: password,
        login: 1
    })
    }).then(response => response.json()).then(responseJson => {   
        console.log(responseJson)
        this.setState({
            errorCheck: responseJson.error
        })
    }).catch(error => {
        console.log("error")
    })
    // console.log(errorCheck);
    console.log(request); 
    console.log("----ERROR CHECK ----")
    console.log(this.state.errorCheck)
    this.props.navigation.navigate("Second")

}

So when I want to set errorCheck that error comes in...

Thanks!

then(response => response.json()).then(responseJson => {   
    console.log(responseJson)
    this.setState({
        errorCheck: responseJson.error
    })
    this.props.navigation.navigate("Second")
})

=> Add this code this.props.navigation.navigate("Second") of navigation inside the then() method so it will call navigation after updating the state then your error will gone.

=> and try to update the state using setState function not an object so try

    this.setState(function (prevState, props) {
        return { errorCheck: responseJson.error}
    })

it will reduce the time , taken by the object to update the state.

=> So your code will look like

  then(response => response.json()).then(responseJson => {   
    console.log(responseJson)
    this.setState(function (prevState, props) {
        return { errorCheck: responseJson.error}
    })
    this.props.navigation.navigate("Second")
})

setState is asynchronous. So if you unmount the stateful component (by calling navigate) before updating the state then you'll get the warning.

You should use the callback that setState provides instead

.then(response => response.json()).then(responseJson => {   
        console.log(responseJson)
        this.setState({
            errorCheck: responseJson.error
        }, () => {
    this.props.navigation.navigate("Second")
        })

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM