Firebase SDK 9 更新当前用户失败 报user._clone is not a function错误
Firebase SDK v9 更新用户资料报错
user._clone is not a function解决办法 使用Firebase SDK v9版本更新用户个人资料时操作失败,报错堆栈如下:
TypeError: user._clone is not a function at AuthImpl.updateCurrentUser (auth_impl.ts:309) at updateUser (firebase.service.ts:41) at Object.signUp (firebase.service.ts:31) at async handlesubmit (index.tsx:32)
报错指向Firebase SDK中updateCurrentUser方法的源码如下:
async updateCurrentUser(userExtern: User | null): Promise<void> { // The public updateCurrentUser method needs to make a copy of the user, // and also check that the project matches const user = userExtern ? (getModularInstance(userExtern) as UserInternal) : null; if (user) { _assert( user.auth.config.apiKey === this.config.apiKey, this, AuthErrorCode.INVALID_AUTH ); } return this._updateCurrentUser(user && user._clone(this)); }
错误原因
官方公开的User类型本身没有_clone属性,该方法是UserInternal内部类型的私有方法,只有经过SDK内部getModularInstance方法正确转换的用户实例才会携带该方法。如果传入updateCurrentUser的用户实例不符合要求,转换失败就会触发该报错。
常见触发原因:
- 传入的用户实例是手动构造的普通对象,不是Auth API原生返回的实例
- 传入的用户实例来自其他Firebase项目/其他Auth实例
- 对原生返回的User实例做了解构、深拷贝等修改操作,丢失了内部私有属性
解决方案
- 仅更新用户显示名、头像等基础资料时,不要直接调用
updateCurrentUser,使用官方封装的updateProfile方法即可,示例代码:
import { getAuth, updateProfile } from "firebase/auth"; const auth = getAuth(); // 直接传入当前auth实例挂载的currentUser即可 updateProfile(auth.currentUser, { displayName: "你的用户名", photoURL: "头像链接" }) .then(() => { // 更新完成,auth.currentUser会自动同步修改后的值 }) .catch((err) => { // 处理异常 });
- 确实需要调用
updateCurrentUser手动替换当前用户的场景,确保传入的用户实例是当前Auth实例通过signInWithEmailAndPassword、onAuthStateChanged等原生接口返回的未修改的完整实例 - 禁止跨Firebase实例、跨项目传递User实例使用
内容的提问来源于stack exchange,提问作者Femi Oni
相关产品推荐
相关产品推荐

