向Firestore保存数据时出现Unsupported field value错误求助
问题排查与解决方案
这个错误的核心原因是你要保存的nodes或edges对象里混入了函数类型的属性,Firestore不支持存储函数、undefined等非JSON兼容类型的数据。
首次刷新后正常是因为初始的nodes/edges是纯数据结构,没有被React Flow实例添加额外的函数属性;但更新数据后,React Flow会给节点/边对象注入内部方法(比如拖拽、交互相关的函数),这些函数被你一起传入Firestore,就触发了报错。
解决方法
方法1:用JSON序列化过滤函数
最简单的方式是通过JSON序列化/反序列化,自动剔除函数、undefined等不合法字段(因为JSON不支持这些类型):
修改saveToDatabase函数里的数据处理部分:
async function saveToDatabase(data){ if(!currentUser) return // 过滤掉数据中的函数、undefined等非JSON字段 const sanitizedData = JSON.parse(JSON.stringify(data)); var fileName = prompt("Enter the name of file"); while(await checkDatabaseFiles(fileName)){ window.alert("Choose different file name") fileName = prompt("Enter the name of file"); } await setDoc(doc(db,currentUser.uid,fileName),{ timestamp:serverTimestamp(), data:sanitizedData, fileName:fileName }); fetchFromDatabase(currentUser) }
方法2:手动提取需要的字段(更可控)
如果JSON序列化出现循环引用问题(极少数情况),可以手动遍历nodes和edges,只保留你需要的核心属性,比如:
const onSave = async(nodes,edges)=>{ // 手动提取节点必要字段 const sanitizedNodes = nodes.map(node => ({ id: node.id, position: node.position, data: node.data, type: node.type || 'default' // 保留节点类型,没有则用默认值 })); // 手动提取边必要字段 const sanitizedEdges = edges.map(edge => ({ id: edge.id, source: edge.source, target: edge.target, type: edge.type || 'default', animated: edge.animated || false })); const data={ initialNodes:sanitizedNodes, initialEdges:sanitizedEdges } try{ await saveToDatabase(data); } catch(err){ console.log("error in saving into the firestore",err); } }
这样能精准控制要保存的字段,彻底避免混入函数属性。
内容的提问来源于stack exchange,提问作者Frtug
相关产品推荐
相关产品推荐

