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

运行calculateTotal函数报错Cannot access 'usagePrice' before initialization如何解决

问题原因

核心是变量名冲突+JS暂时性死区规则共同导致的报错:

  • 全局作用域已经定义了名为usagePrice的函数
  • 在calculateTotal函数内部,你又通过const usagePrice = usagePrice()声明了一个同名的局部变量
  • 根据JS的块级作用域规则,进入calculateTotal作用域时,JS会先扫描所有const/let声明的变量,将其提升到作用域顶部但不做初始化,这段变量声明语句执行前的区域就叫「暂时性死区」,此区间内访问该变量都会触发未初始化的报错
  • 执行const usagePrice = usagePrice()时,右侧调用usagePrice()会优先匹配当前作用域内的局部usagePrice变量,此时该变量还处于暂时性死区未初始化,就触发了你遇到的报错。
修复方案

有两种常用的修复方式:

  1. 修改局部变量名,避免和外部函数重名
// Adds all totals together
const calculateTotal = () => {
    // 局部变量换个不冲突的名字即可
    const currentUsagePrice = usagePrice();
    const currentPrescriptionPrice = prescriptionPrice();
    const currentLensPackagePrice = lensPackagePrice();
    const currentLensTypePrice = lensTypePrice();

    const total = currentUsagePrice + currentPrescriptionPrice + currentLensPackagePrice + currentLensTypePrice;
    return total;
}
  1. 显式指定调用全局作用域的usagePrice函数(仅适用于浏览器环境)
const usagePrice = window.usagePrice();

另外注意你当前代码里的prescriptionPrice、lensPackagePrice、lensTypePrice三个函数还没有实现,修复完命名问题后还需要补充这三个函数的定义,否则运行时会触发函数未定义的报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 08:45:05