我正在使用firebase登录到我的应用程序。但当我登录时,我只在第一次登录时收到这个错误。如果我关闭并重新打开应用程序,则不会显示此错误。我的功能是
async function confirmCode() {
try {
await confirm.confirm(code).then((userData) => {
setModalVisible(false);
props.navigation.navigate('mTab', {screen: 'Home'});
setCode('');
ToastAndroid.show('User Signed In !', ToastAndroid.SHORT);
user = {
uid: userData.user.uid,
name: '',
phone: userData.user.phoneNumber,
photoURL: userData.user.photoURL,
fcmToken: token,
};
dispatch(set_user(user));
});
} catch (error) {
ToastAndroid.show('Invalid Code !', ToastAndroid.SHORT);
console.log(error);
}
}
这是调试器中的错误
D:NativemessengerMuaznode_modulesreact-nativeLibrariesCoreExceptionsManager.js:179 Warning: Can't perform a React state update 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 a useEffect cleanup function.
您应该这样尝试。
useEffect(() => {
try {
await confirm.confirm(code).then((userData) => {
setModalVisible(false);
props.navigation.navigate('mTab', {screen: 'Home'});
setCode('');
ToastAndroid.show('User Signed In !', ToastAndroid.SHORT);
user = {
uid: userData.user.uid,
name: '',
phone: userData.user.phoneNumber,
photoURL: userData.user.photoURL,
fcmToken: token,
};
dispatch(set_user(user));
});
} catch (error) {
ToastAndroid.show('Invalid Code !', ToastAndroid.SHORT);
console.log(error);
}
}, []);
试着用异步函数包装你的方法,比如:
useEffect(() => {
const myMethod = async () => {
try {
await confirm.confirm(code).then((userData) => {
setModalVisible(false);
props.navigation.navigate('mTab', {screen: 'Home'});
setCode('');
ToastAndroid.show('User Signed In !', ToastAndroid.SHORT);
user = {
uid: userData.user.uid,
name: '',
phone: userData.user.phoneNumber,
photoURL: userData.user.photoURL,
fcmToken: token,
};
dispatch(set_user(user));
});
} catch (error) {
ToastAndroid.show('Invalid Code !', ToastAndroid.SHORT);
console.log(error);
}
}
myMethod()
}, [])
为了确保请求的顺序,你可以引入一个清理功能:
useEffect(() => {
let didCancel = false
const myMethod = async () => {
try {
if(didCancel){
return
}
await confirm.confirm(code).then((userData) => {
setModalVisible(false);
props.navigation.navigate('mTab', {screen: 'Home'});
setCode('');
ToastAndroid.show('User Signed In !', ToastAndroid.SHORT);
user = {
uid: userData.user.uid,
name: '',
phone: userData.user.phoneNumber,
photoURL: userData.user.photoURL,
fcmToken: token,
};
dispatch(set_user(user));
});
} catch (error) {
ToastAndroid.show('Invalid Code !', ToastAndroid.SHORT);
console.log(error);
}
}
myMethod()
return () => {didCancel = true}
}, [])
您可能希望添加code
作为依赖项,因为您的请求依赖于它,或者如果您只想在装载时运行它,则将其保留为空。如果要添加code
,请使用[code]
更新空的[]
Dan在这里解释道:https://github.com/facebook/react/issues/14326