1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

「Cannot read properties of undefined (reading 'reduce')」エラーの原因と解決

Last updated at Posted at 2025-04-13

はじめに

今回はReact × Viteでアプリケーション開発中に Cannot read properties of undefined (reading 'reduce') というエラーがブラウザ上で発生したので、解決方法をまとめます。

症状

Reactアプリケーションで、ブラウザ(Google Chrome)のコンソール上に以下のエラーが表示されました。

[vite] TypeError: Cannot read properties of undefined (reading 'reduce')
    at optionMatcher (cli-options.js:4:15)
    at config.js:6:7
    at config.js:9:1

このエラーは、あるオブジェクトがundefinedなのに対してreduceメソッドを呼び出そうとしていることを意味します。

発生原因

最初は supabase 上のテーブルにデータを登録する関数の引数にundefinedの値が含まれているのが原因ではないかと疑い、以下のように関数の呼び出し元で変換処理を追記しました。

register.tsx
// 登録
const onSubmitUser = async (data: UserForm) => {
    try {
      const formData = {
        ...data,
        // 🔵未定義の場合はnullに変換する処理を追記
        githubId: data.githubId || null,
        qiitaId: data.qiitaId || null,
        xId: data.xId || null,
      };

      // supabaseへの登録処理
      const result = await insertUser(formData);
      if (!result) {
        console.error('ユーザー登録に失敗しました');
      }
      // 登録成功後にトップページへ遷移
      navigate('/'); 
    } catch (error) {
      console.error('Submit error:', error);
    }
  };

しかし、エラーは解消されませんでした。
改めて insertUser 関数を定義しているファイルを確認したところ、以下のインポートが含まれていることに気づきました。

user.ts
import { User } from '../domain/user';
import 'dotenv/config'; // 🔵ココが原因
import { supabase } from '../utils/supabase';
import { UserForm } from '../domain/interfaces/userForm';

dotenv/configNode.js の実行環境でのみ使えるものです。
Vite はクライアントサイドの開発ツールなので、ブラウザ環境ではこのインポートは解決できず、未定義の状態が生まれてしまっていた、というのが原因でした。

解決策

ブラウザ環境で動作するコード(Viteで実行される部分)からdotenv/configのインポートを削除することで、エラーは解消されました。

user.ts
import { User } from '../domain/user';
// 'dotenv/config'のインポートを削除
import { supabase } from '../utils/supabase';
import { UserForm } from '../domain/interfaces/userForm';

終わりに

このエラーは、一見オブジェクトの変換処理の不備などが原因に見えましたが、実際には「Node.js用のコードをフロントエンドに含めてしまった」ことが根本原因でした。
Vite では、クライアントとサーバーのコードの境界に注意したいと思います。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?