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

清除应用数据后Realm与MongoDB Atlas不同步问题求助

问题诊断

清除应用数据后,本地Realm文件、用户会话缓存已被清空,但app.currentUser.isLoggedIn返回true属于内存中的错误状态,实际app.currentUser为空对象。此时你的Realm配置里用了app.currentUser!强制非空断言,会导致Realm同步初始化时用户身份无效,无法从MongoDB Atlas拉取同步数据,最终useObject()和useQuery()返回空。

解决方案

1. 修复用户身份检查,移除强制非空断言

修改getRealmConfig,先校验用户真实有效性,再生成配置:

export const getRealmConfig = (app: App) => {
  // 先确保用户存在且已登录
  if (!app.currentUser || !app.currentUser.isLoggedIn) {
    throw new Error("用户未登录,无法初始化Realm配置");
  }

  const behaviorConfiguration: Realm.OpenRealmBehaviorConfiguration = {
    type: "openImmediately",
  };

  const REALM_CONFIG: Realm.Configuration = {
    schema: [Profile, User, MessageProfile, Article, Post, Feed, Blog],
    schemaVersion: 5,
    sync: {
      flexible: true,
      user: app.currentUser,
      newRealmFileBehavior: behaviorConfiguration,
      existingRealmFileBehavior: behaviorConfiguration,
      onError: (err) => {
        console.error("Realm同步错误:", err);
      }
    }
  };

  return REALM_CONFIG;
};

2. 重新验证用户会话,修复currentUser状态

在UserProvider内部添加会话验证逻辑,确保app.currentUser真实有效:

useEffect(() => {
  const validateUser = async () => {
    if (app.currentUser?.isLoggedIn) {
      try {
        // 刷新AccessToken验证会话有效性
        await app.currentUser.refreshAccessToken();
      } catch (err) {
        // 会话失效,登出用户并跳转登录
        await app.currentUser.logOut();
        navigation.navigate("Login");
      }
    }
  };

  validateUser();
}, [app]);

3. 延迟渲染RealmProvider,确保配置有效

只有当app.currentUser真实存在且登录时,再渲染RealmProvider:

<AppProvider id={app_id}>
  <UserProvider fallback={<Login/>}>
    {app.currentUser && app.currentUser.isLoggedIn ? (
      <RealmProvider {...getRealmConfig(app)}>
        {/* 你的应用内容 */}
      </RealmProvider>
    ) : (
      <Login/>
    )}
  </UserProvider>
</AppProvider>

4. 优化同步错误处理,精准定位问题

在sync的onError回调中添加针对性处理:

sync: {
  // ...其他配置
  onError: (err) => {
    console.error("Realm同步错误详情:", err.message, err.name);
    if (err.name === "InvalidSession") {
      // 会话无效时强制登出
      app.currentUser?.logOut();
      // 跳转登录页
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 04:43:17