使用React+Firebase Auth获取用户数据遇auth/argument-error报错求助
解决React + Firebase Auth 中
auth/argument-error 报错问题 你遇到的这个auth/argument-error(提示"toJSON failed: First argument must be a valid string."),大概率是Firebase Auth版本更新后API不兼容导致的——毕竟你是更新node_modules后出现的问题,甚至直接运行参考仓库代码也触发相同错误,说明仓库依赖的旧版Firebase和当前环境的新版本存在冲突。
下面是具体的排查和解决步骤:
1. 锁定Firebase依赖版本
参考仓库使用的是较旧的Firebase版本,而你更新后可能安装了最新版,其中某些API(比如用户数据序列化、获取用户信息的方法)已经发生了变化。
- 先查看参考仓库的
package.json里的Firebase版本,比如如果是^8.10.0这类,就把你的项目依赖也改成对应的版本:"firebase": "^8.10.0" - 然后执行命令重新安装依赖:
npm install # 或者用yarn yarn install
2. 检查用户数据获取的代码逻辑
如果不想回退版本,需要适配新版Firebase Auth的API:
- 旧版中获取当前用户可能用
firebase.auth().currentUser,新版(v9+)采用模块化API,需要先导入对应的方法:import { getAuth, onAuthStateChanged } from "firebase/auth"; const auth = getAuth(); onAuthStateChanged(auth, (user) => { if (user) { // 正确获取用户数据的方式:手动提取需要的字段 const userData = { uid: user.uid, email: user.email, displayName: user.displayName }; console.log(JSON.stringify(userData)); } else { // 用户未登录的处理逻辑 } }); - 错误的核心原因大概率是你(或参考仓库的代码)尝试直接将
user对象转为JSON,而新版Firebase Auth的用户对象包含了无法直接序列化的内部属性,从而触发toJSON failed错误。
3. 清除缓存并重新构建
有时候缓存会导致依赖版本不生效,执行以下命令清理:
# 清除npm缓存 npm cache clean --force # 删除node_modules和lock文件 rm -rf node_modules package-lock.json # 重新安装依赖 npm install # 重新构建项目 npm run build
4. 验证参考仓库的依赖适配
如果你直接运行参考仓库代码也报错,说明仓库的依赖声明可能没有锁定精确版本,导致npm/yarn安装了新版Firebase。你可以修改仓库的package.json,把Firebase版本锁定为一个明确的旧版本(比如8.10.0),再重新安装依赖运行。
内容的提问来源于stack exchange,提问作者B-hawk
相关产品推荐
相关产品推荐

