You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase Snapshot.val()在Vuex获取数据时返回null问题排查

问题分析与解决方案

嘿,我一眼就揪出导致snapshot.val()返回null的问题啦!

错误根源

问题出在你注册用户时写入Firebase数据库的路径字符串里多了个多余的单引号!

看你registerUsers方法里的这段代码:

firebaseDb.ref(`users/'${userId}`).set({ name: payload.name, email: payload.email, select: payload.select });

这里的路径写成了users/'${userId},多出来的单引号会让用户数据被存在类似users/'abc123(abc123为实际userId)的错误路径下。

而你在handleAuthStateChange里读取数据时用的是正确路径:

firebaseDb.ref(`users/${studentId}`).once('value', snapshot => { ... })

一个路径带单引号,一个不带,自然找不到对应数据,所以snapshot.val()返回null。

修正步骤

只需要把注册时的数据库路径里的单引号删掉就行,修正后的registerUsers方法代码:

registerUsers({}, payload) { 
  firebaseAuth.createUserWithEmailAndPassword(payload.email, payload.password) 
  .then(res => { 
    // 这里可以直接用res.user.uid获取用户ID,比currentUser更稳妥
    const userId = res.user.uid; 
    console.log(res) 
    Notify.create({ message: 'Registration Successful!.', color: 'primary', classes: 'quick' }) 
    // 修正路径,去掉多余的单引号
    firebaseDb.ref(`users/${userId}`).set({ name: payload.name, email: payload.email, select: payload.select }); 
  }) 
  .catch(err => { 
    console.log(err) 
    Notify.create({ message: `${err.message}`, classes: 'quick', color: 'negative' }) 
  }) 
}

额外小提示

你登录方法里的console.log()是空的,建议改成console.log(err),这样调试时能看到具体的错误信息,更方便排查问题~

修改后重新注册用户再登录,handleAuthStateChange里就能正常读取到用户数据啦!

内容的提问来源于stack exchange,提问作者AbdulAzeez Olanrewaju

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 12:47:41