In Expo, Requiring module "fetch", threw an exception: ReferenceError: Can't find variable: self

In Expo, Requiring module "fetch", threw an exception: ReferenceError: Can't find variable: self

我搜索了不同的可能答案,但没有找到任何合适的解决此特定错误的方法。

我在问题标题中提到了确切的错误字符串。当我在我的 ReactNative 应用程序中安装 fetch npm 模块时,这个错误开始出现。在开发过程中,当应用程序在我的 phone 上 launched/loaded 时出现此错误。在安装 fetch 之前,我的应用程序在 phone 上正确加载。在 windows CLI 中没有这样的错误可以帮助我解决问题,它只是表明构建成功。

我正在使用 Expo 进行 ReactNative 应用程序开发。请协助解决这方面的问题。可以在以下附加屏幕(显示堆栈跟踪)中看到更多详细信息:

Package.json

{
    "name": "my-new-project",
    "main": "node_modules/expo/AppEntry.js",
    "private": true,
    "scripts": {
        "start": "expo start",
        "android": "expo start --android",
        "ios": "expo start --ios",
        "eject": "expo eject",
        "test": "node ./node_modules/jest/bin/jest.js --watchAll"
    },
    "jest": {
        "preset": "jest-expo"
    },
    "dependencies": {
        "@expo/samples": "2.1.1",
        "expo": "29.0.0",
        "fetch": "^1.1.0",
        "react": "16.3.1",
        "react-native": "https://github.com/expo/react-native/archive/sdk-29.0.0.tar.gz",
        "react-navigation": "^2.9.3"
    },
    "devDependencies": {
        "jest-expo": "29.0.0"
    }
}

这是一个很奇怪的问题,当我 卸载 fetch 并尝试使用任何其他库时,例如axios,对相同错误(与提取模块相关)的引用仍然出现。我已经重新启动了我的笔记本电脑,并在移动设备上也重新启动了 Expo 应用程序。

我认为 fetch 1.1.0 在 React Native 上不能很好地工作,因为 React Native 使用 JS 核心而不是 NodeJS。 我更喜欢你使用库 axios 或 React Native (https://facebook.github.io/react-native/docs/network.html) 的内置 'fetch'。

npm install axios --save

示例

// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

const axios = require('axios');

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

// Optionally the request above could also be done as
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });  

我已经弄明白了,基本上不是 npm 也不是 NPM fetch 组件问题。基本上在设置项目后,我 运行 npm install expo-cli 当我尝试 运行 expo startnpm start 时,CLI 中出现了哪个消息。此时有可用的新版本 v30.x.x,是的,self 参考问题在旧的 expo 版本中,但不在 v30.x.x 中。

安装后 expo-cli 它与我现有的项目 expo 配置和安装文件不匹配,因此我再次重新设置项目,加载并安装最新版本的库并将项目文件复制到其中。

繁荣!这次申请运行没有任何错误。

在我这边,每次关闭并重新启动电脑时都会触发错误(我在 Ubuntu 16.04 上开发)。

我使用了一个旧答案(2016 年),它完全解决了这个问题:

我补充了:

global.self = global;

进入主 js 文件。

一切都恢复正常了。

expo-cli2.2.4(最新版本)

看来这个问题是由 whatwg-fetch 的新版本产生的。对我有用的解决方案是明确添加旧版本:

npm i whatwg-fetch@2.0.4 要么 yarn add whatwg-fetch@2.0.4

解决方案取自here