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

大城市里の小女人 提交于 2019-12-06 02:08:39

It looks like the issue is produced by the fresh version of whatwg-fetch. The solutions, which works for me is explicit adding the older version:

npm i whatwg-fetch@2.0.4 or yarn add whatwg-fetch@2.0.4

Solution taken from here

Hyphæne Ohmen

On my side, the error was triggered each time I shut down and restart the pc (I develop on Ubuntu 16.04 ).

I used an old answer ( 2016 ) which completely fixed the issue:

I added:

global.self = global;

into the main js file.

And everything is back to normal.

expo-cli is at 2.2.4 ( last version )

I think fetch 1.1.0 cannot work well on React Native because React Native use JS core not NodeJS. I prefer you use library axios or built-in 'fetch' of React Native (https://facebook.github.io/react-native/docs/network.html).

npm install axios --save

Example

// 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);
  }
}

or

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
  });  

I have figured it out, basically it was not the npm neither the NPM fetch component issue. Basically after setting up the project I ran npm install expo-cli which message was appearing in CLI when I try to run expo start or npm start. At this time there was new version available v30.x.x, and YES the self reference issue was in older expo version but not in v30.x.x.

After installing expo-cli it was not matching to my existing project expo configuration and installed files, hence I re-setup the project again, which loaded and installed latest version libraries and coppied the project files into it.

And boom! The application ran without any error this time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!