Firebase 9.1.2出现Cannot read property 'createUserWithEmailAndPassword' of undefined错误求助
我在使用Firebase 9.1.2版本时遇到如下错误:
ERROR TypeError: Cannot read property 'createUserWithEmailAndPassword' of undefined, js engine: hermes
我已经严格参照对应版本的Firebase实现文档复制代码,但问题仍然存在。以下是我的注册代码和Firebase配置代码,希望得到解决建议:
注册代码
import {ScrollView, StyleSheet, View} from 'react-native'; import {useState} from 'react'; import React from 'react'; import {Button, Gap, Header, Input, Loading} from '../../components'; import {colors, useForm} from '../../utils'; import {createUserWithEmailAndPassword} from 'firebase/auth'; import {fireAuth} from '../../config'; import {getDatabase, ref, set} from 'firebase/database'; import {showMessage} from 'react-native-flash-message'; export default function Register({navigation}) { const [form, setForm] = useForm({ fullName: '', job: '', email: '', pass: '', }); const [loading, setLoading] = useState(false); const onContinue = () => { console.log(form); setLoading(true); createUserWithEmailAndPassword(fireAuth, form.email, form.pass) .then(success => { setForm('reset'); setLoading(false); const data = { fullName: form.fullName, job: form.job, email: form.email, }; set(ref(getDatabase(), 'users/' + success.user.uid + '/'), data); }) .catch(error => { const errorMessage = error.message; setLoading(false); showMessage({ message: errorMessage, backgroundColor: colors.error, color: colors.white, }); console.log('register error : ', errorMessage); });
Firebase配置代码
import { initializeApp } from 'firebase/app'; import { getAuth } from 'firebase/auth'; const firebaseConfig = { apiKey: '', authDomain: '', projectId: '', storageBucket: '', messagingSenderId: '', appId: '', measurementId: '', }; const fireApp = initializeApp(firebaseConfig); export const fireAuth = getAuth(fireApp);
排查方向与解决建议
检查
fireAuth的导出与导入
在注册组件的onContinue方法开头添加console.log(fireAuth),查看输出是否为undefined。如果是,确认配置文件的导出语法正确,且导入路径../../config没有错误(比如文件夹层级、文件名大小写)。确认Firebase版本与依赖
执行npm list firebase查看安装版本是否为9.1.2,若版本不符,重新安装指定版本:npm install firebase@9.1.2。同时检查是否存在依赖冲突,可删除node_modules和package-lock.json后重新安装依赖。确保Firebase初始化时机正确
将Firebase配置初始化代码移至项目入口文件(如App.js)中提前执行,避免组件加载时fireAuth还未完成初始化。验证Firebase配置参数
核对firebaseConfig中的所有参数是否与Firebase控制台的项目配置完全一致,尤其是authDomain和apiKey,错误的配置会导致Auth实例初始化失败。确认模块化导入无误
Firebase 9采用模块化API,确保createUserWithEmailAndPassword是从firebase/auth正确导入的,没有使用旧版的命名空间调用方式(如firebase.auth().createUserWithEmailAndPassword)。
内容的提问来源于stack exchange,提问作者Ardhya Chandra

