SPFx开发时报错Property 'Choices'不存在于Promise<IFieldInfo>类型咨询
SPFx PnP JS异步调用报错解决方案
错误产生原因
- 核心问题是
@pnp/sp提供的.get()方法属于异步API,返回值为Promise<IFieldInfo>类型,而非直接返回字段配置对象。代码中没有等待Promise执行完成就直接访问Choices属性,TypeScript检测到类型不匹配就会抛出属性不存在的错误。 - 同时存在隐藏风险:
onInit执行完成前,属性面板配置方法getPropertyPaneConfiguration可能已经触发,此时viewModeOptions仍为null,直接访问this.viewModeOptions[0].key会额外抛出空指针错误。
对应的解决方法
第一步:修正异步调用逻辑
将onInit方法改为异步方法,使用async/await等待接口返回结果后再处理下拉选项,完成后强制刷新属性面板:
public async onInit(): Promise<void> { await super.onInit(); sp.setup({ spfxContext: this.context }); // 等待异步请求返回字段配置结果 const choiceField = await sp.web.lists.getByTitle('Contacts').fields.getByTitle('Department').get(); this.viewModeOptions = choiceField.Choices.map((choice: string, idx: number) => { return { key: idx, text: choice } }); // 强制刷新属性面板,确保异步获取的选项正常渲染 this.context.propertyPane.refresh(); }
第二步:优化属性面板配置,规避空指针
重写SPFx提供的loadPropertyPaneResources方法,保证属性面板在异步资源加载完成后再渲染,同时为属性配置增加空判断逻辑:
protected async loadPropertyPaneResources(): Promise<void> { // 等待onInit逻辑执行完成、选项列表赋值后再加载属性面板 await this.onInit(); } protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration { return { pages: [ { header: { description: strings.PropertyPaneDescription }, groups: [ { groupName: strings.BasicGroupName, groupFields: [ PropertyPaneDropdown('department', { label: 'Department', options: this.viewModeOptions || [], // 做空判断避免空指针报错 selectedKey: this.viewModeOptions?.length ? this.viewModeOptions[0].key : undefined, disabled: !this.viewModeOptions?.length }), ] } ] } ] }; }
内容的提问来源于stack exchange,提问作者John John
相关产品推荐
相关产品推荐

