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

MUI Autocomplete报错:options.filter is not a function 技术求助

解决MUI Autocomplete的options.filter is not a function错误

错误根源

报错的核心是**options不是数组类型**,MUI Autocomplete组件要求options必须是数组,才能调用filter方法。你的代码中handleInputChange函数存在关键问题:

const updatedOptions = await SearchService.get(value);
setOptions(updatedOptions);

这里SearchService.get(value)返回的是完整的HTTP响应对象(和useEffect里的response结构一致),而非后端返回的数组数据response.data.data,导致options被设置为非数组的响应对象,触发filter is not a function错误。

修复方案

1. 修正handleInputChange的数据提取逻辑

和useEffect中的处理保持一致,提取响应里的数组数据:

const handleInputChange = async (value) => {
  const response = await SearchService.get(value);
  // 提取后端返回的数组数据,与useEffect中的处理对齐
  setOptions(response.data.data);
}

2. 优化初始加载的判断逻辑

初始options是空数组[],!options会返回false,导致加载提示无法显示。改成判断数组长度:

options={options.length === 0 ? [{label: 'Loading...', id: 0}] : options}

3. 可选:添加加载状态与请求竞态处理(进阶优化)

新增loading状态控制加载提示,同时用AbortController避免快速输入时的重复请求:

import React, { useState, useEffect, useRef } from 'react';
import TextField from '@mui/material/TextField';
import Stack from '@mui/material/Stack';
import Autocomplete from '@mui/material/Autocomplete';
import SearchService from '../../services/search.services';

export default function Search() {
 const [options, setOptions] = useState([]);  
 const [value, setValue] = useState(null);  
 const [loading, setLoading] = useState(false);
 const controllerRef = useRef(null);

useEffect(() => {
  setLoading(true);
  SearchService.get()
  .then((response) => {
    setOptions(response.data.data);
  })
  .finally(() => {
    setLoading(false);
  });
}, []);

const handleInputChange = async (newValue) => {
  // 取消之前未完成的请求
  if (controllerRef.current) {
    controllerRef.current.abort();
  }
  controllerRef.current = new AbortController();
  
  setLoading(true);
  try {
    const response = await SearchService.get(newValue, {
      signal: controllerRef.current.signal
    });
    setOptions(response.data.data);
  } catch (err) {
    // 忽略请求取消的错误
    if (err.name !== 'AbortError') {
      console.error('请求失败:', err);
      setOptions([]);
    }
  } finally {
    setLoading(false);
  }
}

return (
 <Stack spacing={2} sx={{ width: 300 }}>
      <Autocomplete
   filterOptions={(x) => x}
   options={loading ? [{label: 'Loading...', id: 0}] : options}
   value={value}
   onInputChange={(event, newValue) => {
     handleInputChange(newValue)
   }}
   
   renderInput={params => (
     <TextField
       {...params}
       label="Select an option"
       variant="outlined"
       disabled={loading}
     />
   )}
 />
 </Stack>
   );
  }

验证要点

  • 确认SearchService.get返回的响应结构与useEffect中一致,后端数据确实在response.data.data字段中
  • 检查handleInputChange调用后,options是否被设置为数组类型(可通过console.log验证)

内容的提问来源于stack exchange,提问作者Ventrity Customer Service

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 20:55:22