Skip to content
TheChatArchiveThe Chat Archive
DeepSeekdeepseek-r1-0528· DeepSeekHugging Face LMArena Human Preference 140K

У меня выдаёт такую ошибку в консоли? Чтобы это могли значить? "constructor: ƒ Object()…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Qwenqwen3-235b-a22b’s answer.
  1. User

    У меня выдаёт такую ошибку в консоли? Чтобы это могли значить? "constructor: ƒ Object() { [native code] } VM37968 ingredients-category.tsx:24 bun and ingredients is undefined VM37968 ingredients-category.tsx:20 constructor: ƒ Object() { [native code] } VM37968 ingredients-category.tsx:24 bun and ingredients is undefined VM37968 ingredients-category.tsx:27 Uncaught TypeError: Cannot read properties of undefined (reading 'forEach') at eval (VM37968 ingredients-category.tsx:27:21) at mountMemo (VM37666 react-dom.development.js:17225:19) at Object.useMemo (VM37666 react-dom.development.js:17670:16) at useMemo (VM37663 react.development.js:1651:21) at eval (VM37968 ingredients-category.tsx:21:77) at renderWithHooks (VM37666 react-dom.development.js:16305:18) at updateForwardRef (VM37666 react-dom.development.js:19221:20) at beginWork (VM37666 react-dom.development.js:21631:16) at HTMLUnknownElement.callCallback (VM37666 react-dom.development.js:4164:14) at Object.invokeGuardedCallbackDev (VM37666 react-dom.development.js:4213:16)"

    вот код:

    import { forwardRef, useMemo } from 'react'; import { TIngredientsCategoryProps } from './type'; import { TIngredient } from '@utils-types'; import { IngredientsCategoryUI } from '../ui/ingredients-category'; import { useSelector } from '../../services/store'; import { selectConstructor } from '../../services/slices/constructorSlice';

    export const IngredientsCategory = forwardRef< HTMLUListElement, TIngredientsCategoryProps

    (({ title, titleRef, ingredients }, ref) => { /** TODO: взять переменную из стора */ const burgerConstructor = useSelector(selectConstructor);

    console.log('constructor:', burgerConstructor);

    const ingredientsCounters = useMemo(() => { const { bun, ingredients } = burgerConstructor; if (!bun && !ingredients) { console.log('bun and ingredients is undefined'); } const counters: { [key: string]: number } = {}; ingredients.forEach((ingredient: TIngredient) => { if (!counters[ingredient._id]) counters[ingredient._id] = 0; counters[ingredient._id]++; }); if (bun) counters[bun._id] = 2; return counters; }, [burgerConstructor]);

    return ( ); });

  2. DeepSeek Assistant

    Ошибка возникает из-за попытки доступа к свойству ingredients объекта burgerConstructor, которое может быть undefined. Давайте разберем проблему и исправим код:

    Проблема:

    1. В начальном состоянии burgerConstructor возвращает { bun: undefined, ingredients: undefined }.
    2. При деструктуризации const { bun, ingredients } = burgerConstructor мы получаем ingredients = undefined.
    3. При вызове ingredients.forEach(...) возникает ошибка, так как forEach нельзя вызвать для undefined.

    Решение:

    1. Инициализировать ingredients пустым массивом по умолчанию.
    2. Убрать лишние логи (они мешают в продакшене).
    3. Добавить проверку перед использованием ingredients.

    Исправленный код:

    export const IngredientsCategory = forwardRef<
      HTMLUListElement,
      TIngredientsCategoryProps
    >(({ title, titleRef, ingredients }, ref) => {
      const burgerConstructor = useSelector(selectConstructor);
      
      const ingredientsCounters = useMemo(() => {
        // Добавляем fallback для деструктуризации
        const { bun, ingredients: constructorIngredients = [] } = burgerConstructor || {};
        const counters: { [key: string]: number } = {};
    
        // Всегда используем массив (пустой, если данных нет)
        constructorIngredients.forEach((ingredient: TIngredient) => {
          counters[ingredient._id] = (counters[ingredient._id] || 0) + 1;
        });
    
        if (bun) counters[bun._id] = 2;
        
        return counters;
      }, [burgerConstructor]);
    
      return (
        <IngredientsCategoryUI
          title={title}
          titleRef={titleRef}
          ingredients={ingredients}
          ingredientsCounters={ingredientsCounters}
          ref={ref}
        />
      );
    });
    

    Пояснения:

    1. burgerConstructor || {} - гарантирует, что деструктуризация не сломается при null/undefined.
    2. ingredients: constructorIngredients = [] - устанавливает пустой массив по умолчанию.
    3. Убраны console.log чтобы избежать "засорения" консоли.
    4. Оптимизирован счетчик: (counters[ingredient._id] || 0) + 1.

    Дополнительные рекомендации:

    1. Проверьте редьюсер constructorSlice - он должен возвращать объект с полем ingredients типа массив (даже пустой) вместо undefined. Пример корректного начального состояния:
    const initialState = {
      bun: null,
      ingredients: [] // вместо undefined
    };
    
    1. Если используете TypeScript, добавьте типизацию для burgerConstructor:
    interface IConstructorState {
      bun: TIngredient | null;
      ingredients: TIngredient[]; // гарантированно массив
    }
    

    После этих изменений ошибка Cannot read properties of undefined исчезнет, так как мы больше не пытаемся вызвать forEach на undefined.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.