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

Svelte中解锁功能调用API遇TypeError错误求助

问题分析与解决方案

错误根源

出现TypeError: Cannot read properties of undefined (reading 'password')主要是这几个问题:

  1. 变量大小写混乱:代码里混用Isavailablepassword(大写I)和isavailablepassword(小写i),导致返回的是未定义变量,后续逻辑直接出错。
  2. 重复定义函数:两次声明getAuthorizedUserPassword,后定义的覆盖了前一个,而且后一个里的console.log写在异步then外面,根本拿不到异步返回的值,完全无效。
  3. API封装未执行:原PackagingApi是个自执行函数但没加执行括号,导致它是个函数而非包含方法的对象,调用getAuthorizedUserPassword时会直接出问题。

修复步骤

1. 修正API封装

先把PackagingApi改成可直接调用的对象,补上自执行括号:

export const PackagingApi = (function (apiUrl) {
  apiUrl = 'http://localhost:5183';
  return {
    getAuthorizedUserPassword: async (authorizedUserPassword) =>
      HttpRequest.get(`${apiUrl}/api/Auth/${authorizedUserPassword}`),
    SetStationBlocked: async (status, lineCode) => {
      // 补充SetStationBlocked的实际实现,确保和后端接口匹配
    }
  };
})(); // 必须加这个括号,让函数立即执行返回对象

2. 清理重复代码,统一变量命名

删掉重复的getAuthorizedUserPassword定义,统一用驼峰命名规范避免大小写错误:

let isAvailablePassword = null;

const getAuthorizedUserPassword = (authorizedUserPassword) => {
  return PackagingApi.getAuthorizedUserPassword(authorizedUserPassword)
    .then((response) => {
      // 先打印响应确认结构,和Postman返回对比
      console.log('API实际响应:', response);
      // Postman返回是{data: {password: true}},所以取response.data.password
      isAvailablePassword = response.data.password;
      return isAvailablePassword;
    })
    .catch(handleError);
};

3. 优化解锁逻辑,避免重复锁定

原代码每次密码错误递归调用unlockLine会重复执行锁定操作,改成只锁定一次,递归只做密码验证:

const unlockLine = () => {
  // 只执行一次生产线锁定
  PackagingApi.SetStationBlocked(1, lineCode);

  const checkPassword = () => {
    const inputPassword = prompt("Linea Bloqueada \n Ingresa la contraseña del supervisor", "");
    if (!inputPassword) return; // 用户取消输入时终止流程

    getAuthorizedUserPassword(inputPassword)
      .then((isValid) => {
        if (isValid) {
          PackagingApi.SetStationBlocked(0, lineCode);
          alert("生产线已解锁");
        } else {
          alert("Contraseña Incorrecta \n Ingresa la contraseña Correcta para desbloquear");
          checkPassword();
        }
      })
      .catch(() => {
        alert("验证请求失败,请重试");
        checkPassword();
      });
  };

  checkPassword();
};

4. 验证响应结构

在getAuthorizedUserPassword的then里打印response,确认实际返回的结构和Postman一致,如果发现response直接是{password: true}(比如HttpRequest已经解析了外层data),就把response.data.password改成response.password。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 15:01:10