Calling async method from instanced Object gives error: TypeError: Object(...) is not a function

Calling async method from instanced Object gives error: TypeError: Object(...) is not a function

我目前正在开发一个用于教育目的的应用程序,并且面临一个可能微不足道但无法解决的问题。

所以基本上我试图从外部 API 获取一些数据(为此使用 Axios)。我已将我的代码划分为要导出到 index.js 文件的模块,并从中实例化新对象并调用我的异步方法 getResults(),其中 return 应该给我来自 API 的数据。从那时起得到错误

TypeError: Object(...) is not a function.

这是一个示例代码:

模块Search.js:

export default class Search {
  constructor(query, num) {
    this.query = query;
    this.num = num;
  }

  async getResults() {
    const url = 'API_URL';
    const key = 'API_KEY';
    try {
      const res = await axios(`${url}?query=${this.query}&number=${this.num}&apiKey=${key}`);
      this.result = res.data.results;
      console.log(this.result);
    } catch (error) {
      console.log(error);
    }
  }
}

这里是 index.js 文件:

import Search from "./models/Search";
const s = new Search('cheese', 2);
s.getResults()

最后控制台出现错误:

TypeError: Object(...) is not a function
    at Search._callee$ (Search.js:42)
    at tryCatch (runtime.js:65)
    at Generator.invoke [as _invoke] (runtime.js:303)
    at Generator.prototype.<computed> [as next] (runtime.js:117)
    at asyncGeneratorStep (Search.js:5)
    at _next (Search.js:7)
    at eval (Search.js:7)
    at new Promise (<anonymous>)
    at Search.eval (Search.js:7)
    at Search.getResults (Search.js:65)

我可能在这里做错了什么,任何帮助和见解将不胜感激。谢谢。

await axios(`${url}?query=${this.query}&number=${this.num}&apiKey=${key}`);

这是创建错误的行,

axios 是您尝试用作 function

的对象

您可能希望使用 axios 提供的 get/post 方法来调用您的端点

await axios.get(`${url}?query=${this.query}&number=${this.num}&apiKey=${key}`);

你可以看看你想怎么用axioshttps://github.com/axios/axios