首页 > 解决方案 > 如何修复“RealmObject 不能作为函数调用”realm-js 错误?

问题描述

在使用 Realm-js 的 react-native 项目中,我刚刚创建了应用程序的克隆,集成了所有库,并复制了所有 src 目录。

该应用程序构建安装并在 Android 上运行。

当我通过身份验证流程(利用领域来存储身份验证数据)时,我最终得到一个错误:

[错误:RealmObject 不能作为函数调用]

登录功能:

async function login(username, password) {
    try {
      const result = await Api.login({
        username: username,
        pass: password,
      });

      const userAuthResult = await Db.updateAuth(result);
      setUserAuth(userAuthResult);
    } catch (err) {
      console.log('[ ERROR ]:', err)
      if (!err.message || err.message.includes('Network Error')) {
        throw new Error('Connection error');
      }
      throw new Error('Wrong username or password');
    }
  }

我把问题缩小到Db.updateAuth(...)

更新认证:

export const updateAuth = (params) => {
  console.log(' [ HERE 1 ]')
  const auth = {
    id: params.id,
    token: params.token,
    refreshToken: params.refresh_token,
    tokenExpiresAt: Math.floor(Date.now() / 1000) + 600, //params.expires_at,
    federatedToken: params.federatedToken ?? '',
    federatedTokenExpiresAt: params.federatedTokenExpiresAt ?? 0,
    username: params.username,
    name: params.name,
    roleName: params.role_name,
    roleId: params.role_id,
    lastLogin: Math.floor(Date.now() / 1000),
  };
  console.log(' [ HERE 2 ]')

  realm.write(() => {
    console.log(' [ HERE 3 ]')

    realm.create('Authorizations', auth, 'modified'); // PROBLEM
  });

  return auth;
};

检查架构,我发现没有 federatedToken 属性,但在 auth 更新对象中,有两个。不知道为什么它不会在原始的非克隆应用程序中引发错误。

授权架构:

AuthorizationsSchema.schema = {
  name: 'Authorizations',
  primaryKey: 'id',
  properties: {
    id: 'int',
    token: 'string',
    refreshToken: 'string',
    tokenExpiresAt: 'int',
    username: 'string',
    name: 'string',
    roleName: 'string',
    roleId: 'int',
    lastLogin: 'int',
  },
};

Realm.js(类声明)-> https://pastebin.pl/view/c903b2e2

从领域实例化:

let realm = new Realm({
  schema: [
    schema.AccountSchema,
    schema.AuthorizationsSchema,
    schema.AvailableServiceSchema,
    schema.FederatedTokensSchema,
    schema.NoteSchema,
    schema.PhotoSchema,
    schema.PhotoUploadSchema,
    schema.PrintQueueSchema,
    schema.ProductSchema,
    schema.ReportSchema,
    schema.ServicesSchema,
    schema.UploadQueueJobSchema,
    schema.InvoicesSchema,
    schema.TestSchema
  ],
  schemaVersion: 60,
  deleteRealmIfMigrationNeeded: true,
  //path: './myrealm/data',
});

这会记录 1、2 和 3 语句。问题似乎来自“问题”行。我不确定这个错误到底意味着什么,因为领域的回购中似乎没有任何关于它的内容,并且在应用程序中克隆了它,这条线没有问题。我还可以看到其他行稍后在用户流中抛出类似的错误

有谁知道这是关于什么的?或者我可以在哪里了解更多信息?

反应原生:v64.2

realm-js:10.6.0(从 v10.2.0 克隆的应用程序)

MacOS:11.3(M1架构)

标签: react-nativerealmreact-native-androidrealm-js

解决方案


为了创建你有第一个调用,realm.write像这样的方法。

const storeInDataBase = (res,selectedfile) => {
    try{
        realm.write(() => {
            var ID =
            realm.objects(DocumentConverstionHistory).sorted('HistoryID', true).length > 0
            ? realm.objects(DocumentConverstionHistory).sorted('HistoryID', true)[0]
                .HistoryID + 1
            : 1;
            realm.create(DocumentConverstionHistory, {
                HistoryID: ID,
                Name:`${selectedfile.displayname}.pdf`,
                Uri:`file://${res.path()}`,
                Date: `${new Date()}`
            });
        })
    }catch(err){
        alert(err.message)
    }
}

这是架构文件

export const DATABASENAME = 'documentconverter.realm';
export const DocumentConverstionHistory = "DocumentConverstionHistory"
export const DocumentConverstionHistorySchema = {
    name: "DocumentConverstionHistory",
    primaryKey: 'HistoryID',
    properties: {
        HistoryID: {type: 'int'},
        Name: {type: 'string'},
        Uri: {type: 'string?'},
        Type: {type: 'string?'},
        Size: {type: 'string?'},
        Date: {type: 'date?'}
    }
  };
  

推荐阅读