React Native更新Firebase实时数据库触发Maximum call stack size exceeded报错
问题原因
核心问题是函数命名冲突:
你自定义的更新方法命名为update,和从firebase/database导入的Firebase官方更新方法update重名。当你在方法内部执行update(ref(...), {profile})时,实际是在递归调用你自己写的这个update方法,而非Firebase的更新方法,才会出现无限循环,最终抛出调用栈溢出错误。
另外你还存在两个影响功能的隐性问题:
profile状态中没有存储uid字段,拼接数据库路径users/${profile.uid}/时会取到undefined,导致更新路径错误- 更新时传入
{profile}会给所有字段多套一层profile父级节点,不符合常规的用户数据结构设计
修复方案
按以下步骤修改代码即可:
- 重命名自定义的更新方法,避免和Firebase的
update冲突 - 在
profile状态中补充uid字段的存储 - 调整更新时传入的数据结构
修改后的核心代码参考:
// 导入部分无需改动 import {getDatabase, ref, set, update, onValue} from 'firebase/database'; export default function UpdateProfile({navigation}) { const [profile, setProfile] = useState({ fullName: '', profession: '', email: '', uid: '', // 新增uid字段 }); const [password, setPassword] = useState(''); useEffect(() => { getData('user').then(res => { setProfile({ fullName: res.data.fullName, profession: res.data.profession, email: res.data.email, photo: res.photo, uid: res.uid, // 补充存储uid,根据你getData返回的结构调整字段名 }); }); }, []); // 重命名方法,避免命名冲突 const updateProfile = () => { console.log('profile: ', profile); const db = getDatabase(); // 此处调用的是导入的Firebase update方法,不会再递归 update(ref(db, `users/${profile.uid}/`), profile) // 直接传profile,不要套{profile} .then(res => { console.log('success: ', res); }) .catch(err => { console.log('fak'); showMessage({ message: err.message, type: 'default', backgroundColor: colors.error, color: colors.white, }); }); }; // 其余代码不变,只需要修改按钮的onPress绑定 return ( {/* 其余结构不变 */} <Button title="Save Profile" onPress={updateProfile} /> ) }
额外提示
不要将用户密码明文存储在Firebase实时数据库中,密码相关操作请通过Firebase Auth的官方接口实现,避免数据泄露风险。
内容的提问来源于stack exchange,提问作者Dragonarc
相关产品推荐
相关产品推荐

