调用DocumentReference.set()传入无效数据,Firebase连接失败求助
解决Firestore DocumentReference.set() 无效数据报错
这个报错的核心是你传给set()方法的数据里存在Firestore不接受的内容,常见原因和修复方式如下:
检查变量是否为undefined
先看你打印的userName, email, password输出,如果其中某个值是undefined,Firestore会直接抛出这个错误。比如用户输入框没填全,或者变量名拼写错误(比如username和userName大小写不一致),导致变量未正确赋值。
修复:确保所有字段都有有效值,或者给undefined的字段设置默认值,比如:firebase.firestore().collection("users").doc("id0002").set({ user_name: userName || "", user_email: email || "", user_password: password || "", });检查数据类型是否合法
Firestore不支持存储函数、Symbol、循环引用的对象等类型。如果你的userName/email/password里包含这类特殊值,也会触发报错。比如某个变量是一个DOM元素而不是字符串,就会出问题。
修复:确保所有字段都是字符串、数字、布尔值、数组、普通对象这些Firestore支持的类型,必要时用toString()转换(比如处理输入框值时)。检查是否存在未初始化的状态
如果是在React/Vue这类框架里,状态变量可能还没初始化就调用了onSignupPress,导致变量值为undefined。比如userName是用useState声明的,但初始值设成了undefined而不是空字符串。
修复:初始化状态时给默认空字符串:const [userName, setUserName] = useState(""); const [email, setEmail] = useState(""); const [password, setPassword] = useState("");
另外,建议给set()方法加上错误捕获,能看到更具体的报错信息:
const onSignupPress = async () => { console.log(userName, email, password); try { await firebase.firestore().collection("users").doc("id0002").set({ user_name: userName, user_email: email, user_password: password, }); console.log("数据写入成功"); } catch (error) { console.error("写入失败:", error); } };
内容的提问来源于stack exchange,提问作者Rimzzz
相关产品推荐
相关产品推荐

