首页 > 解决方案 > 在辅助函数中调用 axios 时无法读取属性“then”

问题描述

我将 axios 调用分离到另一个名为 ApiMethods.js 的文件中。

现在,每当我尝试在 ApiMethods.js 中使用“uploadSpecFile”函数时,都会收到以下错误:

未捕获的类型错误:无法读取未定义的属性“then”

这是辅助方法:

export function uploadSpecFile(formData, engineId) {
    return
    axios({
        method: 'post',
        url: `/api/engineData/spec-files/${engineId}/files/upload`,
        data: formData,
        config: {
            headers: { 'Content-Type': 'multipart/form-data' }
        }
    })
}

我在这里使用它:

import {  uploadSpecFile } from '/ApiMethods';

// error occurs here  **
uploadSpecFile(bodyFormData, this.props.engineId).then(response => {

        this.setState({
            selectedFile: response.data,
            file: null
        });
    })
    .catch(response => {
    });

有什么我做错了吗?

谢谢!

标签: reactjsecmascript-6axios

解决方案


您正在返回undefined,因为axios与 return 语句不在同一行。

只需将axios请求移到同一行,它就会按预期工作。

export function uploadSpecFile(formData, engineId) {
  return axios({
    method: "post",
    url: `/api/engineData/spec-files/${engineId}/files/upload`,
    data: formData,
    config: {
      headers: { "Content-Type": "multipart/form-data" }
    }
  });
}

推荐阅读