[英]Why am I getting the following React Native warning: Can't perform a React state update on an unmounted component
[英]When i use Async/Await i get the warning of : Can't perform a React state update on an unmounted component
我已经解决了这个问题,但我不知道它为什么会起作用......当我使用 Async/Await 时,错误仍然存在
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
}
},[])
但是当我使用承诺时,它似乎有效
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
}
},[])
就个人而言,我认为在 Promise 中,一个动作是异步持续的。无论组件是否仍然呈现,它都会返回数据。 另一方面,使用 Async/Await,如果组件不再渲染,数据的获取将被中断,如果我弄错了,请纠正我
不要手动更改 React 引用,因为 React 可以重新分配它。 创建自己的标志:
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
}
},[])
或者,如果您想以正确的方式做事,可以使用AbortController
:
https://medium.datadriveninvestor.com/aborting-cancelling-requests-with-fetch-or-axios-db2e93825a36
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.