You need to enable JavaScript to run this app. React中使用Credential Management API报PasswordCredential未定义如何解决
优惠活动
大模型
产品
解决方案
定价
更多

React中使用Credential Management API报PasswordCredential未定义如何解决

报错原因及解决方案

'PasswordCredential' is not defined 报错通常对应三种场景,解决方法如下:

  • 场景1:ESLint校验抛出的编译报错
    PasswordCredential 是浏览器宿主环境提供的API,不属于ECMAScript标准内置对象,ESLint默认未配置该全局变量,因此会触发未定义报错。
    解决方法:在项目根目录的.eslintrc(或.eslintrc.json等等效配置文件)中添加全局变量声明:
{
  "globals": {
    "PasswordCredential": "readonly",
    "FederatedCredential": "readonly"
  }
}

如果是Create React App创建的未暴露ESLint配置的项目,可以在报错的代码文件顶部加注释临时忽略校验:

/* global PasswordCredential */
  • 场景2:TypeScript项目缺少类型定义
    如果是TypeScript项目,需要手动补充Credential Management API的类型定义,在项目的typings.d.ts(或其他全局类型声明文件)中添加如下内容:
interface PasswordCredentialData {
  id: string;
  password: string;
  name?: string;
  iconURL?: string;
}

declare class PasswordCredential {
  constructor(data: PasswordCredentialData);
  readonly type: 'password';
  readonly id: string;
  readonly password: string;
  readonly name?: string;
  readonly iconURL?: string;
}

interface Navigator {
  credentials: {
    store(credential: PasswordCredential): Promise<void>;
    get(options?: any): Promise<Credential | null>;
    preventSilentAccess(): Promise<void>;
  }
}
  • 场景3:浏览器运行时报未定义
    如果是页面实际运行时抛出的错误,说明当前浏览器不支持Credential Management API,使用前需要增加兼容性判断,避免页面崩溃:
if ('PasswordCredential' in window && navigator.credentials) {
  const cred = new PasswordCredential({
    id: this.state.user,
    password: this.state.password
  })
  navigator.credentials.store(cred)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 02:36:04