从UseEffect获取react本机导航身份验证流的内存泄漏错误



我正在尝试设置react本机导航身份验证流,但我给出了一个错误:;

警告:无法对未安装的组件执行React状态更新。这是一个非操作,但它表明应用程序中存在内存泄漏。若要修复此问题,请取消useEffect清理函数中的所有订阅和异步任务

错误很可能是由此处的代码引起的。我以前在得到不同的错误时修复了它,但现在它出现了内存泄漏错误。

React.useEffect(() => {
// Fetch the token from storage then navigate to our appropriate place
const bootstrapAsync = async () => {
let userToken;
try {
userToken = await SecureStore.getItemAsync(LOGIN_KEY);
// IF USER ALREADY LOGGED IN CREATE NEW TOKEN TO KEEP USER LOGGED IN
if(userToken!==null){
let email = await SecureStore.getItemAsync(USER_NAME)
let loginPassword = await SecureStore.getItemAsync(USER_PASSWORD)
authContext.signIn({email,loginPassword})
.then(res=> {
if(res.response.status ==401){
authContext.signOut()
}
console.log(res)
})
.catch(err=>{ console.log(err)})
}
console.log("userTokennn ", userToken )
} catch (e) {
// Restoring token failed
console.log("boostrapError", e)
}
// After restoring token, we may need to validate it in production apps
// This will switch to the App screen or Auth screen and this loading
// screen will be unmounted and thrown away.
dispatch({ type: 'RESTORE_TOKEN', token: userToken });
};
bootstrapAsync();
}, []);

此外,我试着使用清理功能,但没有像这样工作;

};
return ()=> bootstrapAsync();
}, []);

其余代码都在这里;

const authContext = React.useMemo(
() => ({
signIn: async (data) => {
// In a production app, we need to send some data (usually username, password) to server and get a token
// We will also need to handle errors if sign in failed
// After getting token, we need to persist the token using `SecureStore`
// In the example, we'll use a dummy token
//SEND LOGIN INFO TO SERVER
return await postSignIn(data.email, data.loginPassword)
.then(async(res)=>{
token = res.data.token
await SecureStore.setItemAsync(LOGIN_KEY, token);
await SecureStore.setItemAsync(USER_NAME, data.email )
await SecureStore.setItemAsync(USER_PASSWORD, data.loginPassword )
dispatch({ type: 'SIGN_IN', token: token });
})
.catch((err)=>{ console.log("sign in error", err); return err})
},

signOut: () => dispatch({ type: 'SIGN_OUT' }),
signUp: async (data) => {
// In a production app, we need to send user data to server and get a token
// We will also need to handle errors if sign up failed
// After getting token, we need to persist the token using `SecureStore`
// In the example, we'll use a dummy token
dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
},
}),
[]

);

由于api调用的异步性,有时它们会在组件卸载后完成,例如用户访问一个页面,数据开始加载,但在加载完成之前,用户已经导航到另一个页面
这里有一些解决方案。

  1. 您可以跟踪安装在状态中的组件
const [mounted, setMounted] = useState(true);
React.useEffect(() => {
if (mounted) {
bootstrapAsync();
}
return () => {
setMounted(false);
};
}, []);
  1. 从react使用库中使用类似useAsync的smth,它负责处理这一问题

最新更新