You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase Auth报错:Cannot read property 'auth' of undefined 求助

问题:Cannot read property 'auth' of undefined 错误排查

我一直在寻找该错误的解决方案,奇怪的是上周代码完全正常,但今天无法运行。我想使用Firebase Auth为我的应用创建注册页面,却持续出现Cannot read property 'auth' of undefined错误。以下是我的firebase.js和signupScreen.js代码,问题似乎出在onRegisterPress函数中。

firebase.js

import { initializeApp } from "firebase/app";
import { sendPasswordResetEmail, getAuth} from "firebase/auth";
import 'firebase/compat/firestore';

// TODO: Replace the following with your app's Firebase project configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
               //config code
    
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

export const sendPasswordReset = async (email) => {
    try {
      await sendPasswordResetEmail(auth, email);
      alert("Password reset link sent!");
    } catch (err) {
      console.error(err);
      alert(err.message);
    }
  };

export {app} ;

// // Initialize Realtime Database and get a reference to the service
// const database = getDatabase(app);

signupScreen.js

//SignupScreen.js
import {React, useState} from "react";
import { TouchableOpacity, TextInput, View, Text, Image } from "react-native";
import {styles} from "../styles/Styling";
import { acuitisLogo} from "../assets/images";
import { firebase } from "../components/firebase";


export default function SignupScreen({ navigation }) {
  const [email, setEmail] = useState('');
  const [password,setPassword] = useState('');
  const [confirmPassword,setConfirmPassword] = useState('');
  const [firstName,setFirstName] = useState('');
  const [lastName,setLastName] = useState('');

  const onRegisterPress = () => {
    if (password !== confirmPassword) {
        alert("Passwords don't match.")
        return
    }

    firebase
        .auth()
        .createUserWithEmailAndPassword(email, password)
        .then((response) => {
            const uid = response.user.uid
            const data = {
                id: uid,
                email,
                firstName,
                lastName,
            };
            const usersRef = firebase.firestore().collection('users')
            usersRef
                .doc(uid)
                .set(data)
                .then(() => {
                    navigation.navigate('Home', {user: data})
                })
                .catch((error) => {
                    alert(error)
                });
        })
        .catch((error) => {
            alert(error)
    });
}

    return (
      <View style={ styles.stackpagecontainer }>
        {/* <Image source = {acuitisLogo} style = {{alignSelf: "center", marginTop: 100}} /> */}
        <Text style = {styles.title}> Sign up </Text>
        <View style={styles.inputView}>
          <TextInput
          style = {styles.inputButtonText}
          placeholder="First Name"
          placeholderTextColor="#949494"
          onChangeText={(firstName) => setFirstName(firstName)} />
          </View>
          <View style={styles.inputView}>
          <TextInput
          style = {styles.inputButtonText}
          placeholder="Last Name"
          placeholderTextColor="#949494"
          onChangeText={(lastName) => setLastName(lastName)} />
          </View>
        <View style={styles.inputView}>
          <TextInput
          style = {styles.inputButtonText}
          placeholder="Email"
          placeholderTextColor="#949494"
          onChangeText={(email) => setEmail(email)} />
          </View>
          <View style={styles.inputView}>
          <TextInput
          style = {styles.inputButtonText}
          placeholder="Password"
          placeholderTextColor="#949494"
          secureTextEntry={true}
          onChangeText={(password) => setPassword(password)} />
          </View>
          <View style={styles.inputView}>
          <TextInput
          style = {styles.inputButtonText}
          placeholder="Confirm Password"
          placeholderTextColor="#949494"
          secureTextEntry={true}
          onChangeText={(confirmPassword) => setConfirmPassword(confirmPassword)} />
          </View>
        <TouchableOpacity style = {styles.appButtonContainer} onPress={() => {onRegisterPress(); navigation.navigate("Login")}}>
        <Text style = {styles.appButtonText}> Submit </Text>
        </TouchableOpacity>  
        <TouchableOpacity style = {styles.existingButtonContainer} onPress={() => navigation.navigate("Login")}>
        <Text style = {styles.loginButtonText}> ALREADY A MEMBER? - SIGN IN HERE </Text>
        </TouchableOpacity>
      </View>
    );
  }
解决方案

错误根源是Firebase SDK版本调用方式不匹配:你在firebase.js中使用了Firebase v9+的模块化API,但在signupScreen.js里仍用旧版命名空间式调用(firebase.auth()、firebase.firestore()),且导入的firebase对象实际未定义。

步骤1:修正firebase.js的导出逻辑

修改firebase.js,导出初始化好的auth和Firestore实例,而非仅导出app:

import { initializeApp } from "firebase/app";
import { sendPasswordResetEmail, getAuth, createUserWithEmailAndPassword } from "firebase/auth";
import { getFirestore, doc, setDoc } from "firebase/firestore";

const firebaseConfig = {
    // 你的配置代码
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);

export const sendPasswordReset = async (email) => {
    try {
        await sendPasswordResetEmail(auth, email);
        alert("Password reset link sent!");
    } catch (err) {
        console.error(err);
        alert(err.message);
    }
};

// 导出需要的实例和方法
export { auth, db, createUserWithEmailAndPassword, doc, setDoc };

步骤2:更新signupScreen.js的调用逻辑

替换旧的命名空间调用,改用模块化API:

//SignupScreen.js
import {React, useState} from "react";
import { TouchableOpacity, TextInput, View, Text, Image } from "react-native";
import {styles} from "../styles/Styling";
import { acuitisLogo} from "../assets/images";
import { auth, db, createUserWithEmailAndPassword, doc, setDoc } from "../components/firebase";


export default function SignupScreen({ navigation }) {
  const [email, setEmail] = useState('');
  const [password,setPassword] = useState('');
  const [confirmPassword,setConfirmPassword] = useState('');
  const [firstName,setFirstName] = useState('');
  const [lastName,setLastName] = useState('');

  const onRegisterPress = async () => {
    if (password !== confirmPassword) {
        alert("Passwords don't match.")
        return
    }

    try {
        const response = await createUserWithEmailAndPassword(auth, email, password);
        const uid = response.user.uid;
        const data = {
            id: uid,
            email,
            firstName,
            lastName,
        };
        await setDoc(doc(db, 'users', uid), data);
        navigation.navigate('Home', {user: data});
    } catch (error) {
        alert(error.message);
    }
}

    return (
      <View style={ styles.stackpagecontainer }>
        {/* <Image source = {acuitisLogo} style = {{alignSelf: "center", marginTop: 100}} /> */}
        <Text style = {styles.title}> Sign up </Text>
        <View style={styles.inputView}>
          <TextInput
          style = {styles.inputButtonText}
          placeholder="First Name"
          placeholderTextColor="#949494"
          onChangeText={(firstName) => setFirstName(firstName)} />
          </View>
          <View style={styles.inputView}>
          <TextInput
          style = {styles.inputButtonText}
          placeholder="Last Name"
          placeholderTextColor="#949494"
          onChangeText={(lastName) => setLastName(lastName)} />
          </View>
        <View style={styles.inputView}>
          <TextInput
          style = {styles.inputButtonText}
          placeholder="Email"
          placeholderTextColor="#949494"
          onChangeText={(email) => setEmail(email)} />
          </View>
          <View style={styles.inputView}>
          <TextInput
          style = {styles.inputButtonText}
          placeholder="Password"
          placeholderTextColor="#949494"
          secureTextEntry={true}
          onChangeText={(password) => setPassword(password)} />
          </View>
          <View style={styles.inputView}>
          <TextInput
          style = {styles.inputButtonText}
          placeholder="Confirm Password"
          placeholderTextColor="#949494"
          secureTextEntry={true}
          onChangeText={(confirmPassword) => setConfirmPassword(confirmPassword)} />
          </View>
        <TouchableOpacity style = {styles.appButtonContainer} onPress={() => {onRegisterPress(); navigation.navigate("Login")}}>
        <Text style = {styles.appButtonText}> Submit </Text>
        </TouchableOpacity>  
        <TouchableOpacity style = {styles.existingButtonContainer} onPress={() => navigation.navigate("Login")}>
        <Text style = {styles.loginButtonText}> ALREADY A MEMBER? - SIGN IN HERE </Text>
        </TouchableOpacity>
      </View>
    );
  }

补充说明

Firebase v9+采用模块化API设计,目的是减少打包体积,需按需导入具体方法,不再支持firebase.auth()这类命名空间调用。若偏好旧版语法,可安装firebase/compat包,但官方推荐使用模块化API。

内容的提问来源于stack exchange,提问作者Dayna Starr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 16:22:50