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

ReactJS中Uncaught TypeError: getOptionLabel非函数问题求助

解决Material UI Autocomplete的getOptionLabel类型错误

错误原因分析

  1. getOptionLabel参数类型错误:你把getOptionLabel赋值为subLocationData.map(option => option),这会返回一个数组,但Autocomplete要求getOptionLabel必须是接收单个option参数并返回字符串的函数,这直接触发了TypeError: getOptionLabel Prop is not a function。
  2. options格式不匹配:你的subLocationData是包含单个对象的数组([{0:"Intent1", 1:"Intent2", 2:"Intent3"}]),Autocomplete的options需要是可遍历的项数组(比如字符串数组、结构化对象数组),当前格式无法被组件正确解析。

修复步骤

1. 转换数据源格式

先把subLocationData转换为标准的字符串数组:

// 提取对象中的值,转换为字符串数组
const formattedOptions = Object.values(subLocationData[0]);

如果API返回的是动态数据,确保每次获取后都做这个转换。

2. 修正getOptionLabel属性

将getOptionLabel改为符合要求的函数:

getOptionLabel={(option) => option}

因为现在options是字符串数组,直接返回option即可;如果后续用对象数组,这里要返回对象中对应显示的字段(比如option.name)。

3. 调整其他关联逻辑

确保selectedNames的状态与新的options格式匹配,同时简化onChange逻辑。

完整修复后的代码

import { useState } from 'react';
import { Autocomplete, Chip, TextField } from '@mui/material';

// Initialize useState
const [selectedNames, setSelectedNames] = useState([]);

// 原始数据源
const subLocationData = [{
    0: "Intent1",
    1: "Intent2",
    2: "Intent3"
}];

// 转换为标准字符串数组
const formattedOptions = Object.values(subLocationData[0]);

// 渲染组件
return (
    <Autocomplete
        multiple
        id="fixed-tags-demo"
        value={selectedNames}
        onChange={(event, newValue) => {
            // 直接更新选中值,过滤空值的逻辑可根据需求保留
            setSelectedNames(newValue.filter(option => option));
        }}
        options={formattedOptions}
        getOptionLabel={(option) => option}
        renderTags={(tagValue, getTagProps) =>
            tagValue.map((option, index) => (
                <Chip
                    label={option}
                    {...getTagProps({ index })}
                />
            ))
        }
        style={{ width: 500 }}
        renderInput={(params) => (
            <TextField 
                {...params} 
                label={formData.location.value} 
                placeholder={formData.location.value} 
            />
        )}
    />
);

额外注意事项

  • 如果API返回的数据源结构可能变化(比如数组长度不止1),可以用subLocationData.flatMap(item => Object.values(item))来处理多个对象的情况。
  • 若后续需要使用结构化对象作为options(比如每个项包含id和name),要同步调整getOptionLabel为(option) => option.name,并确保selectedNames存储的是对应的对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 09:51:16