You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

执行CRUD操作调用sweetalert2.fire时触发Uncaught TypeError错误求助

解决Uncaught TypeError: sweetalert2__WEBPACK_IMPORTED_MODULE_2___default(...).fire is not a function错误

以下是几种常见的排查和解决方法:

  • 检查导入方式是否正确
    不同版本的SweetAlert2导出结构可能有差异,确保导入语句匹配当前版本:

    • 对于SweetAlert2 v11+,标准导入方式:
      import Swal from 'sweetalert2';
      
      之后直接调用Swal.fire(...)即可。
    • 如果导入默认导出仍有问题,尝试命名导入:
      import * as Swal from 'sweetalert2';
      
  • 升级SweetAlert2到最新稳定版
    老版本可能存在导出逻辑的bug,运行命令升级:

    # npm
    npm install sweetalert2@latest
    
    # yarn
    yarn add sweetalert2@latest
    

    升级后重新检查导入和调用代码。

  • 避免CDN与模块导入混用
    如果项目中同时通过CDN引入<script>标签和npm/yarn安装导入SweetAlert2,会导致全局对象与模块导出冲突,只保留其中一种引入方式即可。

  • 检查webpack/babel配置影响
    若使用webpack或babel,某些模块转换插件可能修改了默认导出结构:

    • 检查@babel/plugin-transform-modules-commonjs这类插件是否开启,必要时调整配置,或者改用命名导入方式。

正确使用示例

import Swal from 'sweetalert2';

// 删除用户操作示例
const handleDeleteUser = (userId) => {
  Swal.fire({
    title: '确认删除?',
    text: '此操作不可撤销,用户数据将永久删除',
    icon: 'warning',
    showCancelButton: true,
    confirmButtonText: '确认删除',
    cancelButtonText: '取消'
  }).then((result) => {
    if (result.isConfirmed) {
      // 执行删除API请求
      fetch(`/api/users/${userId}`, { method: 'DELETE' })
        .then(() => {
          Swal.fire('删除成功', '用户已被删除', 'success');
          // 更新页面用户列表
        })
        .catch(err => {
          Swal.fire('删除失败', '操作过程中出现错误', 'error');
        });
    }
  });
};

内容的提问来源于stack exchange,提问作者Rohit Chorge-Patil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 00:35:06