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

React Native中Realm的useRealm钩子报错:未找到Realm上下文

解决Realm Context Not Found错误

错误的核心原因是**useRealm()的调用位置错误**:你在App组件中直接调用了useRealm(),但App组件是<RealmProvider>的父组件,<RealmProvider>是在App的return语句中才渲染的,所以App本身并没有处于Realm的上下文环境中,自然无法获取Realm实例。

修复方案

  • 删除App组件中的const realm = useRealm();这行代码,App的职责是提供RealmProvider,不需要直接访问Realm。
  • 所有需要访问Realm的逻辑(比如读写操作),必须放在被<RealmProvider>包裹的子组件中(比如你的RestOfApp组件)。

修改后的完整代码

import React from 'react';
import Realm from 'realm';
import {createRealmContext} from '@realm/react';
import CButton from './src/components/atoms/CButton';

class Profile extends Realm.Object<Profile> {
  _id!: Realm.BSON.ObjectId;
  name!: string;
  static schema = {
    name: 'Profile',
    properties: {
      _id: 'objectId',
      name: 'string',
    },
    primaryKey: '_id',
  };
}

const realmConfig: Realm.Configuration = {
  schema: [Profile],
};

const {RealmProvider, useRealm, useObject, useQuery} =
  createRealmContext(realmConfig);

const RestOfApp = () => {
  const realm = useRealm();
  const changeProfileName = (profileToChange: Profile, newName: string) => {
    realm.write(() => {
      profileToChange.name = newName;
    });
  };

  return <CButton onClick={() => {}}>Test</CButton>;
};

function App(): JSX.Element {
  // 移除了错误的useRealm调用
  return (
    <RealmProvider fallback={() => null}>
      <RestOfApp />
    </RealmProvider>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 21:52:09