“未定义的不是函数”,不太可能的React Native + Class-Transformer错误

ih99xse1  于 2023-03-13  发布在  React
关注(0)|答案(1)|浏览(113)

我想我会把我遇到的一个罕见但难以调试的React Native类转换器问题的经验贴出来。
关于如何在react-native中使用set up class-transformer已经说了很多,如果我们想方便地处理复杂类型,比如未序列化的javascript Dates being returned from an API,react-native是一个非常需要的库。长话短说,你需要设置一个nichebabel插件数组来让那些装饰器工作,我在babel.config.js文件中的设置如下:

module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    [
      'module:react-native-dotenv',
      {
        moduleName: '@env',
        allowUndefined: true,
      },
    ],
    'react-native-reanimated/plugin',
    'babel-plugin-transform-typescript-metadata',
    '@babel/plugin-transform-flow-strip-types',
    ['@babel/plugin-proposal-decorators', {legacy: true}],
  ],
};

一切都很顺利,直到我尝试使用类转换器来输入存储在异步存储中的JSON对象(以创建使用之间的状态持久性)时,我遇到了这个问题:

在控制台上:

ERROR  TypeError: undefined is not a function, js engine: hermes
 LOG  Running "App" with {"rootTag":251,"initialProps":{}}
 ERROR  Invariant Violation: "App" has not been registered. This can happen if:
* Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it and restart it in the current project.
* A module failed to load due to an error and `AppRegistry.registerComponent` wasn't called., js engine: hermes
ckx4rj1h

ckx4rj1h1#

事实上,它正在创建一个不变冲突,这意味着在React Native术语中,这个问题发生在渲染之前,因此不是使用问题,而是编译问题。
人们可能会认为,所有的ts配置和babel预设都很好,只要它在其他地方工作并正确编译,但这只适用于react-native函数中的代码,而我的全局上下文的初始化是在App函数(仅次于index.js的最高函数)之外进行的,如下所示:

export const GlobalContext = React.createContext<GlobalContextInterface | null>({state: initialState, dispatch: () => null});

我用这些空值初始化它,以避免处理可能的空值(因为我知道App函数的第一行将把上下文设置为useReducer状态并分派值,所以它实际上永远不会为空)。
然而我的错误在于我处理这个伪初始化的方式。将state设置为{}就足够了,但是我创建了一个State类型的空对象。由于这个对象是在react原生函数之外创建的,它没有被babel装饰器插件拾取,也没有正确编译。

相关问题