我正在尝试使用firebase在react native上构建一个简单的身份验证应用程序。在App.js文件中,我正在使用useEffect钩子在我的应用程序中初始化firebase实例,并且还声明了一个函数,用于在用户登录或注销时更新本地状态(loggedIn)。当我尝试使用电子邮件和密码登录时,我可以显示“注销”按钮,但此警告消息会弹出:
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 %s.%s, a useEffect cleanup function,
in LoginForm (at App.js:25)
- node_modules\react-native\Libraries\YellowBox\YellowBox.js:63:8 in console.error
- node_modules\expo\build\environment\muteWarnings.fx.js:27:24 in error
- node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:645:36 in warningWithoutStack
- node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:20432:6 in warnAboutUpdateOnUnmountedFiberInDEV
- node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:18518:41 in scheduleUpdateOnFiber
- node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:11484:17 in dispatchAction
* [native code]:null in dispatchAction
* src\components\LoginForm.js:13:8 in LoginForm
* src\components\LoginForm.js:25:24 in onButtonPress
- node_modules\regenerator-runtime\runtime.js:45:44 in tryCatch
- node_modules\regenerator-runtime\runtime.js:271:30 in invoke
- node_modules\regenerator-runtime\runtime.js:45:44 in tryCatch
- node_modules\regenerator-runtime\runtime.js:135:28 in invoke
- node_modules\regenerator-runtime\runtime.js:145:19 in Promise.resolve.then$argument_0
- node_modules\promise\setimmediate\core.js:37:14 in tryCallOne
- node_modules\promise\setimmediate\core.js:123:25 in setImmediate$argument_0
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:146:14 in _callTimer
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:194:17 in _callImmediatesPass
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:458:30 in callImmediates
* [native code]:null in callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:407:6 in __callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:143:6 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:142:17 in __guard$argument_0
* [native code]:null in flushedQueue
* [native code]:null in invokeCallbackAndReturnFlushedQueue
该如何解决?
App.js(主条目文件):
import { StyleSheet, View } from "react-native";
import { Button } from "react-native-elements";
import { Header, Spinner, CardSection } from "./src/components/common";
import LoginForm from "./src/components/LoginForm";
import firebase from "firebase";
export default function App() {
const [loggedIn, setLoggedIn] = useState(null);
const renderContent = () => {
switch (loggedIn) {
case true:
return (
<CardSection>
<View style={{ flex: 1 }}>
<Button
title="Log Out"
onPress={() => firebase.auth().signOut()}
/>
</View>
</CardSection>
);
case false:
return <LoginForm />;
default:
return (
<CardSection>
<Spinner size="large" />
</CardSection>
);
}
};
useEffect(() => {
if (!firebase.apps.length) {
try {
firebase.initializeApp({
apiKey: "AIzaSyC6zF09VjQS9kYOK6OsiBrXeVdMWQEt-5k",
authDomain: "auth-b4c8c.firebaseapp.com",
databaseURL: "https://auth-b4c8c.firebaseio.com",
projectId: "auth-b4c8c",
storageBucket: "auth-b4c8c.appspot.com",
messagingSenderId: "270113167666",
appId: "1:270113167666:web:3c74e7b22f7c6cf6c6df2b",
measurementId: "G-9EMRRJ6GKX"
});
firebase.auth().onAuthStateChanged(user => {
if (user) {
setLoggedIn(true);
} else {
setLoggedIn(false);
}
});
} catch (err) {
console.error("Firebase initialization error.", err.stack);
}
}
}, []);
return (
<View>
<Header headerText="Authentication" />
{renderContent()}
</View>
);
}
LoginForm.js文件:
import React, { useState } from "react";
import { View, Text, StyleSheet } from "react-native";
import { Card, CardSection, Input, Spinner } from "./common";
import { Button } from "react-native-elements";
import firebase from "firebase";
const LoginForm = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [errorMessage, setErrorMessage] = useState("");
const [loading, setLoading] = useState(false);
const onLoginSuccess = () => {
setEmail("");
setPassword("");
setLoading(false);
setErrorMessage("");
};
const onLoginFail = () => {
setErrorMessage("Authentication failed. Try again.");
setLoading(false);
};
const onButtonPress = async () => {
setErrorMessage("");
setLoading(true);
try {
await firebase.auth().signInWithEmailAndPassword(email, password);
onLoginSuccess();
} catch (e1) {
console.log(e1);
try {
await firebase.auth().createUserWithEmailAndPassword(email, password);
onLoginSuccess();
} catch (e2) {
console.log(e2);
onLoginFail();
}
}
};
return (
<Card>
<CardSection>
<Input
secureTextEntry={false}
placeholder="abc@example.com"
label="Email:"
value={email}
onChangeText={text => setEmail(text)}
/>
</CardSection>
<CardSection>
<Input
secureTextEntry={true}
placeholder="password"
value={password}
onChangeText={password => setPassword(password)}
label="Password:"
/>
</CardSection>
{errorMessage ? (
<Text style={styles.errorTextStyle}>{errorMessage}</Text>
) : null}
<CardSection>
{loading ? (
<Spinner size="small" />
) : (
<View style={{ flex: 1 }}>
<Button title="Log in" onPress={() => onButtonPress()} />
</View>
)}
</CardSection>
</Card>
);
};
const styles = StyleSheet.create({
errorTextStyle: {
fontSize: 20,
alignSelf: "center",
color: "red"
}
});
export default LoginForm;
所有其他组件(例如Header / Spinner等)与状态没有任何直接关系,并且仅出于表示/样式目的,因此在此不包括它们的代码。
答案 0 :(得分:1)
问题在于,由于在renderContent
函数中使用了大小写切换,因此在某些时候您不再呈现LoginForm。因此将其卸载,但是与此同时,将对其执行状态更新并引发错误。
查看您的代码,可能会在调用await firebase.auth().signInWithEmailAndPassword(email, password);
时在LoginForm中发生问题。
实际上,一旦登录完成,就会触发firebase.auth().onAuthStateChanged();
并卸载LoginForm,但是会调用onLoginSuccess
并更新LoginForm状态。
尝试删除onLoginSuccess
,因为自卸载以来,该表单在再次呈现后应重新设置。
答案 1 :(得分:0)
如警告中所述,您应提供清除功能,并确保状态更新适当地发生。
按如下所示更新代码,然后检查是否可行。希望对您有所帮助。
let isMounted = false;
useEffect(()=> {
if(!isMounted) {
/* your authentication and state update code */
isMounted = true;
}
return () => {
isMounted = false;
}
}, [isMounted]);
有关更多详细信息,请参见以下评论: