React项目中Firebase Auth/存储正常但Firestore setDoc无法创建文档
问题分析与解决方案
核心问题1:uploadTask.on 参数顺序错误
你当前调用 uploadTask.on 时参数顺序完全错误,Firebase 存储的 uploadBytesResumable.on() 方法第一个参数必须指定事件类型(比如 'state_changed'),后续才是状态回调、错误回调、完成回调。你现在把错误回调放在了第一个参数位置,导致完成回调根本不会被触发,自然里面的 setDoc 代码完全没执行。
核心问题2:异步操作未正确等待,错误未捕获
就算完成回调能触发,你在 getDownloadURL 的 then 里用了 async 函数,但没有捕获其中的错误;同时外面的 toast.success 和 setLoading(false) 没有等待存储上传、Profile更新、Firestore写入这些异步操作完成,导致用户提前看到成功提示,但实际后续操作可能失败。
修正后的代码
// 替换原Signup.jsx中的上传及后续逻辑部分 const userCredential = await createUserWithEmailAndPassword(auth, email, password) const user = userCredential.user const storageRef = ref(storage, `images/${username}`) const uploadTask = uploadBytesResumable(storageRef, file) // 修正uploadTask.on的参数顺序 uploadTask.on('state_changed', // 可选:上传状态变化回调(比如进度显示) (snapshot) => { const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100 console.log('Upload is ' + progress + '% done') }, // 错误回调 (error) => { setLoading(false) toast.error(error.message) }, // 完成回调 async () => { try { const downloadURL = await getDownloadURL(uploadTask.snapshot.ref) // 更新用户Profile await updateProfile(user, { displayName: username, photoURL: downloadURL }) // 写入Firestore await setDoc(doc(db, 'users', user.uid), { uid: user.uid, displayName: username, phone, email, sex: userSex, photoURL: downloadURL }) // 所有异步操作完成后再提示成功 toast.success('Account created') setLoading(false) } catch (err) { setLoading(false) toast.error('Failed to complete setup: ' + err.message) } } )
额外排查点
- Firestore安全规则:检查你的Firestore安全规则是否允许创建
users文档。默认规则是只允许认证用户读写自己的文档,确保规则类似:rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /users/{userId} { allow create, read, update, delete: if request.auth != null && request.auth.uid == userId; } } } - 变量合法性:确认
phone、userSex这些变量都有正确取值,没有未定义的情况,否则setDoc可能因字段值异常失败。 - Firebase控制台日志:打开Firebase控制台的Firestore > 日志,查看是否有写入失败的错误记录,能直接定位问题。
内容的提问来源于stack exchange,提问作者fathi93
相关产品推荐
相关产品推荐

