簡體   English   中英

React Native - 警告:無法對卸載的組件執行 React 狀態更新

[英]React Native - Warning: Can't perform a React state update on an unmounted component

在此處輸入圖片說明 在此處輸入圖片說明

我正在嘗試使用 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 等)與狀態沒有任何直接關系,僅用於演示/樣式目的,因此我沒有在此處包含它們的代碼。

問題是,由於您在renderContent函數中的 switch-case,在某些時候您不再呈現 LoginForm。 因此它被卸載,但同時對其執行狀態更新並拋出錯誤。

查看您的代碼,當await firebase.auth().signInWithEmailAndPassword(email, password);時,問題可能發生在 LoginForm 中await firebase.auth().signInWithEmailAndPassword(email, password); 叫做。 事實上,一旦登錄完成, firebase.auth().onAuthStateChanged(); 觸發並卸載 LoginForm,但onLoginSuccess並更新 LoginForm 狀態。

嘗試刪除onLoginSuccess ,一旦卸載它再次呈現表單,它應該被重置。

正如警告中指定的那樣,您應該提供清理功能並確保狀態更新正確發生。

像下面這樣更新您的代碼並檢查它是否有效。 我希望這對你有幫助。

let isMounted = false;
useEffect(()=> {
  if(!isMounted) {
    /* your authentication and state update code */
    isMounted = true;
  }
  return () => {
    isMounted = false;
  }
}, [isMounted]);

有關更多詳細信息,請參閱以下評論:

https://github.com/material-components/material-components-web-react/issues/434#issuecomment-449561024

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM