React 应用程序抛出 axios_1.default.post 不是函数错误

ren*_*kre 3 javascript typescript reactjs axios

我正在使用 TypeScript 开发 React 应用程序。我有以下简单的发布方法:

import React, { useState } from 'react';
import axios from 'axios';

await axios.post('api/account/register', {
    FirstName: formData.firstName,
    LastName: formData.lastName,
    Username: formData.email,
    Password: formData.password,
    IsLocked: true,
    Role: 'Admin',
});
Run Code Online (Sandbox Code Playgroud)

下面是js文件中的相应代码:

const axios_1 = __importDefault(require("axios"));
const react_1 = __importStar(require("react"));

yield axios_1.default.post('api/account/register', {
    FirstName: formData.firstName,
    LastName: formData.lastName,
    Username: formData.email,
    Password: formData.password,
    IsLocked: true,
    Role: 'Admin',
});
Run Code Online (Sandbox Code Playgroud)

它抛出此异常:axios_1.default.post is not a function error。我安装了最新版本的 axios。

在此输入图像描述

在此输入图像描述

以下是ts.config文件:

{
  "compileOnSave": true,
  "compilerOptions": {
    "module": "commonjs",
    "jsx": "react",
    "skipLibCheck": true,
    "strict": true,
    "moduleResolution": "node",
    "target": "es6",
    
  }
}
Run Code Online (Sandbox Code Playgroud)

dependenciespackage.json 内:

"dependencies": {
    //other packages   
    "axios": "1.4.0"
  },
Run Code Online (Sandbox Code Playgroud)

在这里你可以找到几乎所有的项目文件:

https://github.com/erkaner/reactapp-peeraid

我检查了其他一些帖子,但找不到解决此问题的方法。有什么帮助吗?

0xt*_*xts 7

经过广泛的测试和调试,并通过不同的来源查找问题后,问题实际上出在create-react-app. 本质上,为浏览器axios提供了一个commonjs模块,但 webpack 配置create-react-app似乎没有正确处理它。这个问题帮我确认了。

我做了什么?

我进入Register.js文件并添加了一个console.logforaxios__1来查找,它是 -

{
  default: "/static/media/axios.77dc18bde70a91f68d85.cjs"
}
Run Code Online (Sandbox Code Playgroud)

axios实例

这没有任何意义,我看到扩展名是,.cjs并且还发现如果我.js从项目中删除所有文件,它就可以工作!为什么?所有文件都是 es 模块,而 webpack(来自Register.js源代码)似乎作为axioses 模块导入 -

Object.defineProperty(exports, "__esModule", { value: true });
const axios_1 = __importDefault(require("axios"));
Run Code Online (Sandbox Code Playgroud)

看到这里设置__esModuletrue,所以它会尝试像这样导入它。现在,正如开头提到的,这是create-react-appwebpack 配置不正确的错误,所以请继续阅读。

那么,如何解决呢?

覆盖 webpack 配置create-react-app以确保 babel 正确转换并导入代码。我们可以使用cracoreact-app-rewired。我决定和react-app-rewired——

  1. 安装react-app-rewirednpm i -D react-app-rewired.
  2. 在项目根目录创建一个文件config-overrides.js,并用以下代码片段填充它 -
const getCacheIdentifier = require('react-dev-utils/getCacheIdentifier');

const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';

module.exports = function override(config, webpackEnv) {
  console.log('overriding webpack config...');

  const isEnvDevelopment = webpackEnv === 'development';
  const isEnvProduction = webpackEnv === 'production';
  const loaders = config.module.rules[1].oneOf;

  loaders.splice(loaders.length - 1, 0, {
    test: /\.(js|mjs|cjs)$/,
    exclude: /@babel(?:\/|\\{1,2})runtime/,
    loader: require.resolve('babel-loader'),
    options: {
      babelrc: false,
      configFile: false,
      compact: false,
      presets: [
        [
          require.resolve('babel-preset-react-app/dependencies'),
          { helpers: true },
        ],
      ],
      cacheDirectory: true,
      // See #6846 for context on why cacheCompression is disabled
      cacheCompression: false,
      // @remove-on-eject-begin
      cacheIdentifier: getCacheIdentifier(
        isEnvProduction
          ? 'production'
          : isEnvDevelopment && 'development',
        [
          'babel-plugin-named-asset-import',
          'babel-preset-react-app',
          'react-dev-utils',
          'react-scripts',
        ]
      ),
      // @remove-on-eject-end
      // Babel sourcemaps are needed for debugging into node_modules
      // code.  Without the options below, debuggers like VSCode
      // show incorrect code and set breakpoints on the wrong lines.
      sourceMaps: shouldUseSourceMap,
      inputSourceMap: shouldUseSourceMap,
    },
  });

  return config;
};
Run Code Online (Sandbox Code Playgroud)
  1. 修改package.json为使用react-app-rewired而不是react-scripts,像这样 -
...

  "scripts": {
    "start": "set HTTPS=true&&react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-app-rewired eject"
  },

...
Run Code Online (Sandbox Code Playgroud)

就是这样,问题就解决了。

在此输入图像描述