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

使用Firebase Realtime Database读取数据时出现Client is Offline错误

问题原因

Uncaught (in promise) Error: Error: Client is offline.报错触发的核心原因是调用get(child(userDbRef, "User-ID-"+userID))时,Firebase Realtime Database SDK尚未完成和云端的连接初始化,SDK默认优先读取本地缓存,判定客户端离线后直接抛出未捕获异常,你的代码中get()方法只绑定了.then()回调,没有配置.catch()错误处理逻辑,导致异常直接抛出到全局。

修复方案

你可以按以下要求修改代码:

  • 给所有异步操作补充错误捕获逻辑,避免未捕获的promise异常
  • 离线报错时增加自动重试,或改用onValue监听替代单次get请求,onValue会自动等待连接建立后返回数据,不会直接抛出离线错误
修改后的完整代码
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js";

// Your web app's Firebase configuration
const firebaseConfig = {
  apiKey: "AIzaSyAfA1HIkamXEFtDidPkpxaltDVsWpFWepE",
  authDomain: "thundersmmpanel-77fb2.firebaseapp.com",
  databaseURL: "https://thundersmmpanel-77fb2-default-rtdb.firebaseio.com",
  projectId: "thundersmmpanel-77fb2",
  storageBucket: "thundersmmpanel-77fb2.appspot.com",
  messagingSenderId: "867306490186",
  appId: "1:867306490186:web:93407cb6d8b0e9abe9d9b3"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

import {getDatabase, ref, set, get, child, onValue} from "https://www.gstatic.com/firebasejs/9.6.0/firebase-database.js";

const userID = {{user['id']}};
const userName = "{{user['username']}}";
const pointsDb = getDatabase();

// 初始化数据写入
function initailData() {
  set(ref(pointsDb, "User-ID-"+userID),{
      UserName: userName,
      InitialSpent: {{user['spent']}},
      ThisRun: 1
  })
  .then(function(){
      alert("Done");
  })
  .catch(function(error){
      alert("Error "+error);
  });
  console.log("initailData");
}

function runInitialFunction() {
  const userRef = ref(pointsDb, "User-ID-"+userID);
  // 改用onValue监听,自动等待连接就绪
  const unsubscribe = onValue(userRef, (snapshot) => {
    if(snapshot.exists()){
      // 这里写已有数据的处理逻辑
      console.log("用户已有数据", snapshot.val());
    }else{
      initailData();
    }
    // 单次查询完成后取消监听,避免后续数据变更触发回调
    unsubscribe();
  }, (error) => {
    // 错误捕获逻辑
    console.error("数据读取失败", error);
    // 如果是离线错误,3秒后重试
    if(error.message.includes("Client is offline")){
      setTimeout(runInitialFunction, 3000);
    }
  });
  console.log("runInitialFunction");
}
runInitialFunction();

内容的提问来源于stack exchange,提问作者Abdul Basit

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 15:45:01