Firebase用户资料更新问题:注册添加用户名时报错
React Native Firebase注册时添加用户名报错解决
我正在更新React Native应用,希望用户注册时除邮箱和密码外还能设置用户名,但尝试的方法均报错。目前仅需实现注册用户名的功能,相关注册代码如下:
import {Text, TextInput, View, Image, SafeAreaView, TouchableOpacity } from 'react-native' import React, { useState, useLayoutEffect } from 'react' import { authentication} from '../firebase-config'; import { createUserWithEmailAndPassword} from 'firebase/auth'; import { useTailwind } from 'tailwind-rn/dist'; const Registration = ({navigation}) => { const [email, setemail] = useState('') const [password, setpassword] = useState('') const [username, setusername] = useState('') const tailwind = useTailwind(); useLayoutEffect(() => { const unsubscribe = authentication.onAuthStateChanged(user => { if (user) { navigation.navigate("onboarding") } }) return unsubscribe }, []) const Register = () =>{ createUserWithEmailAndPassword(authentication, email, password) .then(authentication, userCredentials => { return userCredentials.user.updateProfile({ displayName: username, }) }) .catch(error => { if (error.code === 'auth/email-already-in-use') { alert('That email address is already in use!'); } if (error.code === 'auth/invalid-email') { alert('That email address is invalid!'); } console.error(error); }); }
运行时出现错误:
[TypeError: undefined is not an object (evaluating 'userCredentials.user.updateProfile')]
问题根源
你在createUserWithEmailAndPassword的.then()回调里多传了一个authentication参数,导致原本应该接收用户凭证的userCredentials变量被替换成了authentication对象,自然找不到user属性,触发undefined错误。
修复方案
直接移除.then()里多余的authentication参数,修正后的Register函数如下:
const Register = () => { createUserWithEmailAndPassword(authentication, email, password) // 移除第一个多余的authentication参数 .then(userCredentials => { return userCredentials.user.updateProfile({ displayName: username, }) }) // 可选:添加then处理更新成功后的逻辑,确保信息同步完成再跳转 .then(() => { navigation.navigate("onboarding"); }) .catch(error => { if (error.code === 'auth/email-already-in-use') { alert('该邮箱已被注册!'); } if (error.code === 'auth/invalid-email') { alert('邮箱格式无效!'); } console.error(error); }); }
额外提示
updateProfile是异步操作,返回Promise,建议在它的.then()里处理页面跳转,避免用户信息未更新完成就进入下一页。- 检查用户名输入框是否正确绑定状态:
<TextInput onChangeText={setusername} value={username} />,确保能正确获取用户输入的用户名。
内容的提问来源于stack exchange,提问作者Hecker
相关产品推荐
相关产品推荐

