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

Realm JS + React Native创建Photo对象时出现‘no internal field’错误求助

解决Realm JS创建Photo对象时的“no internal field”错误

核心问题:Buffer与Realm data类型不兼容

你怀疑的方向是对的——Realm的data类型对应ArrayBuffer,而你使用的Buffer是Node.js环境专属类型,在React Native中并非原生兼容,直接传入会导致Realm无法识别内部字段,触发错误。

修复方法:将Base64字符串直接转为ArrayBuffer

放弃Buffer.from,改用原生方法完成Base64到ArrayBuffer的转换:

// 替换原Buffer转换逻辑
function base64ToArrayBuffer(base64) {
  const binaryString = atob(base64);
  const bytes = new Uint8Array(binaryString.length);
  for (let i = 0; i < binaryString.length; i++) {
    bytes[i] = binaryString.charCodeAt(i);
  }
  return bytes.buffer;
}

// 使用转换函数处理图片
const pictureBase64 = await readFile(path, "base64");
const pictureArrayBuffer = base64ToArrayBuffer(pictureBase64);

之后在创建Photo对象时传入picture: pictureArrayBuffer即可。

其他可能的排查点

1. 确认ResultSchema已注册

你的Photo模型依赖Result嵌入式对象,但代码中仅定义了ResultSchema,需确保Realm初始化时将其加入schema列表:

const realm = await Realm.open({
  schema: [Photo, ResultSchema], // 必须包含ResultSchema
  // 其他同步配置...
});

若未注册ResultSchema,Realm无法识别result字段类型,也可能引发类似错误。

2. 验证userInputs的类型合法性

Photo模型中userInputs定义为{}?(可选混合类型),需确保section.userInputs是可序列化的普通JSON对象,不能包含循环引用、函数或Realm对象实例等不支持的类型。

3. 确保写事务正确执行

Realm的写入操作必须在realm.write()回调中执行,即使你省略了事务代码,也要确认结构正确:

await realm.write(() => {
  const newPhoto = realm.create("Photo", {
    _id: new Realm.BSON.ObjectId(),
    user: user.profile.email,
    userInputs: section.userInputs,
    createdAt: new Date(),
    projectId: new Realm.BSON.ObjectId(projectId),
    annotation: "someString",
    picture: pictureArrayBuffer,
  });
});

修改后的完整创建示例

// 工具函数:Base64转ArrayBuffer
function base64ToArrayBuffer(base64) {
  const binaryString = atob(base64);
  const bytes = new Uint8Array(binaryString.length);
  for (let i = 0; i < binaryString.length; i++) {
    bytes[i] = binaryString.charCodeAt(i);
  }
  return bytes.buffer;
}

// 写事务内创建对象
async function createPhoto(realm, path, user, section, projectId) {
  const pictureBase64 = await readFile(path, "base64");
  const pictureArrayBuffer = base64ToArrayBuffer(pictureBase64);

  return realm.write(() => {
    return realm.create("Photo", {
      _id: new Realm.BSON.ObjectId(),
      user: user.profile.email,
      userInputs: section.userInputs,
      createdAt: new Date(),
      projectId: new Realm.BSON.ObjectId(projectId),
      annotation: "someString",
      picture: pictureArrayBuffer,
    });
  });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:15:48