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

调用showAlert报错Class constructor AlertMessage不可无new调用如何解决

问题根因

  1. 导入语法错误:toast.js 中 showAlert 是命名导出,你使用默认导入语法实际导入的是 AlertMessage 类,直接调用类就会触发Class constructor cannot be invoked without 'new'报错。
  2. 调用时机错误:getStaticProps 是 Next.js 服务端运行的函数,执行环境是 Node.js 没有浏览器的 document、window 对象,就算导入正确,调用操作 DOM 的 showAlert 也不会生效,还会额外触发 DOM 相关报错。

修复步骤

1. 修正导入语句

把页面中的导入代码从:

import showAlert from "../components/toast";

改为命名导入:

import { showAlert } from "../components/toast";

即可解决当前的类型报错。

2. 调整弹窗触发逻辑

弹窗属于客户端交互,不能在服务端函数中调用,需要把错误状态传到页面组件,在客户端副作用中触发:

  • 首先修改 getStaticProps 逻辑,将错误信息通过 props 传递:
if(foundData.status == 500){
  return{
    props: {
      error: "服务器错误,请稍后重试"
    },
    notFound: true,
  }
}
  • 然后在页面组件中引入弹窗组件,在客户端加载完成后触发弹窗:
import { useEffect } from 'react'
import AlertMessage, { showAlert } from "../components/toast";

export default function Page({ data, error }) {
  // 仅在客户端环境执行弹窗逻辑
  useEffect(() => {
    if (error) {
      showAlert(error)
    }
  }, [error])

  return (
    <>
      {/* 必须渲染AlertMessage组件,页面才会生成对应的DOM元素 */}
      <AlertMessage />
      {/* 原有页面内容 */}
    </>
  )
}

3. 可选优化:支持props传入默认提示

可以修改 AlertMessage 组件,支持自定义默认提示内容:

export default class AlertMessage extends Component{
  render(){   
    return(
      <div className="position-fixed bottom-0 end-0 p-3" style={{zIndex: "11"}}>
        <div className="toast align-items-center text-white bg-danger border-0" id="myAlert" role="alert" aria-live="assertive" aria-atomic="true">
        <div className="d-flex">
            <div className="toast-body" id="alertMessage">
                {this.props.defaultMessage || "出现错误,请重试"}
            </div>
            <button type="button" className="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
        </div>
      </div>
    );
  }
}

内容的提问来源于stack exchange,提问作者Soufiane

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 05:45:04