简体   繁体   中英

When i use Async/Await i get the warning of : Can't perform a React state update on an unmounted component

I have already solved this problem, but I don't know why it works... When I use Async/Await the error persists

const [data, setData]= useState([])
const thisComponent = useRef(true)
useEffect(async()=>{

    const http = axios()
    const {data:{restaurants}}= await http.get('/restaurants')
    if(thisComponent.current){
        setData(restaurants)
    }

    return ()=>{
        thisComponent.current=false
    }
},[])

But when I use promises, it seems to work

const [data, setData]= useState([])
const thisComponent = useRef(true)
useEffect(()=>{
    const http = axios()
    http.get('/restaurants').then(({data:{restaurants}})=>{
        if(thisComponent.current){
            setData(restaurants)
        }

    })
    
    return ()=>{
        thisComponent.current=false
    }
},[])

Personally, I think that in promises, an action persists asynchronously.. and it will return the data no matter if the component is still rendered. On the other hand, with Async/Await, the fetch of data will be interrupted if the component is not rendered anymore, please correct me if I am mistaken

Do not manually change a React reference because React can reassign it. Create your own flag:

const [data, setData]= useState([])
const thisComponent = useRef(true)
useEffect(async()=>{
    let mounted = true

    const http = axios()
    const {data:{restaurants}}= await http.get('/restaurants')
    if(mounted){
        setData(restaurants)
    }

    return ()=>{
        mounted=false
    }
},[])

Or if you want to do things the right way, you can use AbortController :

https://medium.datadriveninvestor.com/aborting-cancelling-requests-with-fetch-or-axios-db2e93825a36

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