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

React Native中Android端Realm关闭应用后数据丢失问题求助

React Native Realm数据重启后丢失问题

我在React Native 0.70.6中采用单例模式实现Realm 11.3.0的CRUD操作,应用运行期间数据增删改查一切正常,但关闭应用后所有数据全部丢失。

Realm配置代码

import Realm from 'realm';
// 导入schemas

let realmInstance: Realm;

export const getRealmInstance = async () => {
  if (!realmInstance) {
    realmInstance = await Realm.open({
      schemaVersion: 1.1,
      path: 'localOnly.realm',
      inMemory: false,
      schema: [
       // 添加schemas
       ...Regulations,
      ],
    });
  }
  return realmInstance;
};

Schema实现代码

import {ObjectSchema} from 'realm';

export const RegulationItemSchema: ObjectSchema = {
  name: 'RegulationItem',
  primaryKey: 'id',
  properties: {
    id: 'int',
    text: 'string',
  },
};

export const RegulationSchema: ObjectSchema = {
  name: 'Regulation',
  primaryKey: 'id',
  properties: {
    id: 'int',
    items: 'RegulationItem[]',
  },
};

export default [RegulationSchema, RegulationItemSchema];

使用示例代码

import {getRealmInstance} from '@realmdb/realmConfig';

export const createARegulation = async (regulation: NecessaryRegulation): Promise<void> => {
  const realm = await getRealmInstance();
  realm.write(() => {
    realm.create<Regulation>(
      'Regulation',
      regulation,
    );
  });
};

export const getRegulations = async (): Promise<
  Regulation[] | undefined
> => {
  const realm = await getRealmInstance();
  const regulations = await realm.objects<Regulation>('Regulation');
  if (necessaryRegulations) {
    return JSON.parse(
      JSON.stringify(regulations),
    ) as Regulation[];
  }
  return undefined;
};

// 更多代码

已尝试的解决步骤

  • 将Realm版本从11.0.0升级到11.3.0,无效
  • 在Realm.open配置中添加path参数,尝试过'appDB.realm'和'localOnly.realm'
  • 在Realm.open配置中显式设置inMemory: false

测试环境

  • 仅在Android 11和13的模拟器及物理设备测试,打包APK安装后问题依旧
  • 本地开发环境:
    • Node: v16.17.0
    • npm: 8.15.0
    • react-native: 0.70.6
    • realm: 11.3.0
    • 系统: macOS Ventura 13.x.x M1

问题排查与解决方法

1. 修正Realm文件存储路径

手动指定简单文件名作为path,可能导致文件被存到临时目录,应用重启后被系统清理。Realm默认会将文件放在应用私有持久化目录,建议:

  • 直接删除path参数,使用默认路径;
  • 或者基于默认路径自定义:
// 替换原path配置
path: Realm.defaultPath.replace('.realm', '_localOnly.realm'),

2. 确保写入操作正常完成

添加错误捕获,确认写入过程无异常:

export const createARegulation = async (regulation: NecessaryRegulation): Promise<void> => {
  const realm = await getRealmInstance();
  try {
    realm.write(() => {
      realm.create<Regulation>('Regulation', regulation);
    });
  } catch (error) {
    console.error('数据写入失败:', error);
  }
};

3. 校验PrimaryKey唯一性

确保创建Regulation和RegulationItem时,id是全局唯一值。重复的id会触发Realm的更新逻辑,可能导致数据未正确持久化。

4. 应用退出时显式关闭Realm实例

在应用退出的生命周期钩子中调用关闭方法,确保所有写入操作被持久化:

export const closeRealmInstance = () => {
  if (realmInstance && !realmInstance.isClosed) {
    realmInstance.close();
    realmInstance = undefined;
  }
};

5. 检查Android权限配置

对于Android 10及以下设备,可在AndroidManifest.xml中添加存储权限(Realm默认用内部存储,多数情况不需要,但部分定制ROM可能限制):

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="29"/>

6. 验证Realm文件存在性

通过adb命令查看应用数据目录下的Realm文件:

adb shell run-as com.your.app.package
ls -l files/

如果文件不存在,说明路径配置错误;如果文件存在但大小为0,说明写入操作未成功执行。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 03:03:13