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

Expo React Native中Redux-Toolkit createAsyncThunk报错求助

Expo + Redux-Toolkit: 异步Thunk共存时的编译错误

问题场景

在基于Expo的React Native项目中,定义两个createAsyncThunk函数时,即使仅使用其中一个,也会触发编译错误:

ERROR  [Error: Exception in HostFunction: Compiling JS failed: 2:20:invalid expression Buffer size 613 starts with: 5f5f642866756e6374696f6e28676c6f and has protection mode(s): rw-p]

删除未使用的fetchStationsStatus函数后项目恢复正常,已尝试expo start --clear清除缓存但无效。

可能的原因及解决方案

1. Metro打包器静态解析异常(路径别名或JSON文件问题)

Metro会解析文件中所有代码(即使未被使用),fetchStationsStatus中require("@data/stationsStatus.json")可能存在以下问题:

  • 路径别名未正确配置:检查metro.config.js中@data的别名是否指向正确目录。正确配置示例:
const { getDefaultConfig } = require('expo/metro-config');
const path = require('path');

const config = getDefaultConfig(__dirname);
config.resolver.alias['@data'] = path.resolve(__dirname, './data'); // 替换为你的data目录路径

module.exports = config;
  • JSON文件语法错误:确认stationsStatus.json文件无语法错误(比如缺失逗号、括号不匹配),可以用JSON校验工具检查。

2. 同步require在异步函数中的冲突

异步函数中使用同步require可能触发Metro的打包逻辑异常,尝试替换为动态导入:

export const fetchStationsStatus = createAsyncThunk(
  "stations/fetchStationsStatus",
  async () => {
    console.log(process.env.NODE_ENV);
    if (process.env.NODE_ENV === "test") {
      const data = await import("@data/stationsStatus.json");
      return data.default;
    }
    const response = await api.get("/stationsStatus");
    return response.data;
  }
);

3. 深层缓存未清理

expo start --clear可能未清理所有缓存,尝试以下操作:

  • 删除项目根目录下的node_modules/.cache文件夹
  • 执行npx expo prebuild --clean(仅适用于bare workflow项目)
  • 重启开发环境及设备

4. 同文件多Thunk的打包冲突

尝试将两个Thunk拆分到不同文件中,仅导入需要使用的那个,验证是否还会触发错误。如果拆分后正常,说明Metro对同文件中多个异步Thunk的解析存在异常,可作为临时解决方案。

内容的提问来源于stack exchange,提问作者Paulin.f

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 10:32:13