React-Native 异步函数意外标识符_this2

React-Native async function unexpected identifier _this2

我有这个函数,我想等待它的结果然后使用它:

getUserId = () => {
    fetch("https://www.dummysite.com/mobile/person-id", {
      credentials: "include",
      method: "GET",
      headers: {
        Cookie: this.state.auth_token_res
      }
    }).then(res => {
      let id_obj = JSON.parse(res._bodyText);
      console.log("parsed json", id_obj);
      return id_obj.data;
    });
  };

我想在这个函数中使用它:

async sendID() {
        let user_id = await this.getUserId();
        console.log(user_id);
        OneSignal.sendTags({
          user_id: user_id
        })
          .then(function(tagsSent) {
            // Callback called when tags have finished sending
            console.log("tag is set: ", tagsSent);
          })
          .catch(err => {
            console.log("error", err);
          });
  }

我没有发现任何语法问题,并且应用程序可以编译,但是当它启动时却出现了这个错误:

error image

另一个奇怪的是,如果我在这个屏幕上打开远程调试,我会得到一个不同的错误: error 2

这里说 await 不在异步函数中,但它在异步函数中,而且我的编辑器或 Metro 捆绑器中没有出现语法错误。

您可能错过了一些事情。考虑这些变化。尽管我没有机会对其进行测试,但我相信它会起作用,或者至少会让您走上正轨。

getUserId = () => {
  // return fetch in order to await
  return fetch("https://www.dummysite.com/mobile/person-id", {
    credentials: "include",
    method: "GET",
    headers: {
      Cookie: this.state.auth_token_res
    }
  }).then(res => res.json());
};

// make this an arrow function
sendID = async () => {
  try {
    let user_id = await this.getUserId();
    // after printing then decide what to do here;
    console.log(user_id);

    const tagsSent = await OneSignal.sendTags({
      user_id: user_id
    });
    console.log(tagsSent);

  } catch (err) {
    console.log(err);
  }

}