当前位置: 首页 > 知识库问答 >
问题:

React:TypeError:无法将未定义或null转换为对象

赵晟睿
2023-03-14

我正在运行一个React应用程序。

当我通过路由(单击按钮或链接)进入页面时,页面工作正常,但当我重新加载页面时,页面崩溃。我看不到错误在哪里,控制台和源代码显示为空,这是服务器消息控制台消息。

server: Entrypoint index [big] = index.js index.1af9d975ff74be4d27d9.hot-update.js index.c93bf08301ec20c0dc85.js.map index.c93bf08301ec20c0dc85.js.map
server:    533 modules
server: backend debug read session { csrfToken: '0ae87c36d850008df20b58941bf89072', id: 2 }
server: backend debug {"data":{"currentUser":null}} <= undefined
server: backend debug {"data":{"currentUser":null}} <= undefined
server: backend debug read session {}
server: backend error TypeError: Cannot convert undefined or null to object
server:     at getPrototypeOf (<anonymous>)
server:     at hoistNonReactStatics (/Users/apple/Desktop/dev/bethabit/node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js:71:38)
server:     at resolveComponent (/Users/apple/Desktop/dev/bethabit/node_modules/@loadable/component/dist/loadable.cjs.js:332:3)
server:     at InnerLoadable.loadSync (/Users/apple/Desktop/dev/bethabit/node_modules/@loadable/component/dist/loadable.cjs.js:189:24)
server:     at new InnerLoadable (/Users/apple/Desktop/dev/bethabit/node_modules/@loadable/component/dist/loadable.cjs.js:138:17)
server:     at processChild (/Users/apple/Desktop/dev/bethabit/node_modules/react-dom/cjs/react-dom-server.node.development.js:3048:14)
server:     at resolve (/Users/apple/Desktop/dev/bethabit/node_modules/react-dom/cjs/react-dom-server.node.development.js:3013:5)
server:     at ReactDOMServerRenderer.render (/Users/apple/Desktop/dev/bethabit/node_modules/react-dom/cjs/react-dom-server.node.development.js:3436:22)
server:     at ReactDOMServerRenderer.read (/Users/apple/Desktop/dev/bethabit/node_modules/react-dom/cjs/react-dom-server.node.development.js:3395:29)
server:     at renderToStaticMarkup (/Users/apple/Desktop/dev/bethabit/node_modules/react-dom/cjs/react-dom-server.node.development.js:3969:27)
server:     at process (/Users/apple/Desktop/dev/bethabit/node_modules/@apollo/react-ssr/lib/react-ssr.cjs.js:38:16)
server:     at process._tickCallback (internal/process/next_tick.js:68:7)
server: backend debug read session { id: 3 }
server: backend debug loading <= currentUser
server: backend debug loading <= currentUser
server: backend debug loading <= currentUser
server: backend debug {"data":{"currentUser":{"id":3,"username":"canercak@gmail.com","role":"user","isActive":true,"email":"canercak@gmail.com","__typename":"User"}}} <= currentUser
server: backend debug {"data":{"currentUser":{"id":3,"username":"canercak@gmail.com","role":"user","isActive":true,"email":"canercak@gmail.com","__typename":"User"}}} <= currentUser
server: backend debug {"data":{"currentUser":{"id":3,"username":"canercak@gmail.com","role":"user","isActive":true,"email":"canercak@gmail.com","profile":{"firstName":"Caner","lastName":"Çakmak","fullName":"Caner Çakmak","__typename":"UserProfile"},"auth":{"certificate":null,"facebook":{"fbId":null,"displayName":null,"__typename":"FacebookAuth"},"google":{"googleId":"104801577244556473676","displayName":"Caner Çakmak","__typename":"GoogleAuth"},"github":null,"linkedin":null,"__typename":"UserAuth"},"__typename":"User"}}} <= currentUser
server: backend debug read session {}
server: backend error TypeError: Cannot convert undefined or null to object
server:     at getPrototypeOf (<anonymous>)
server:     at hoistNonReactStatics (/Users/apple/Desktop/dev/bethabit/node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js:71:38)
server:     at resolveComponent (/Users/apple/Desktop/dev/bethabit/node_modules/@loadable/component/dist/loadable.cjs.js:332:3)
server:     at InnerLoadable.loadSync (/Users/apple/Desktop/dev/bethabit/node_modules/@loadable/component/dist/loadable.cjs.js:189:24)
server:     at new InnerLoadable (/Users/apple/Desktop/dev/bethabit/node_modules/@loadable/component/dist/loadable.cjs.js:138:17)
server:     at processChild (/Users/apple/Desktop/dev/bethabit/node_modules/react-dom/cjs/react-dom-server.node.development.js:3048:14)
server:     at resolve (/Users/apple/Desktop/dev/bethabit/node_modules/react-dom/cjs/react-dom-server.node.development.js:3013:5)
server:     at ReactDOMServerRenderer.render (/Users/apple/Desktop/dev/bethabit/node_modules/react-dom/cjs/react-dom-server.node.development.js:3436:22)
server:     at ReactDOMServerRenderer.read (/Users/apple/Desktop/dev/bethabit/node_modules/react-dom/cjs/react-dom-server.node.development.js:3395:29)
server:     at renderToStaticMarkup (/Users/apple/Desktop/dev/bethabit/node_modules/react-dom/cjs/react-dom-server.node.development.js:3969:27)
server:     at process (/Users/apple/Desktop/dev/bethabit/node_modules/@apollo/react-ssr/lib/react-ssr.cjs.js:38:16)
server:     at process._tickCallback (internal/process/next_tick.js:68:7)

这是运行的代码。我尝试删除currentuser、addhabity和许多其他东西,只是为了了解错误的来源。没有结果。如果我通过链接进入页面,一切正常。

HabiddView.web.jsx

const HabitAddView = ({ addHabit, t, currentUser }) => {
  const renderMetaData = () => (
    <Helmet
      title={`${settings.app.name} - ${t('habit.title')}`}
      meta={[
        {
          name: 'description',
          content: t('habit.meta')
        }
      ]}
    />
  );
  return (
    <PageLayout>
      {renderMetaData()}
      <div className="row">
        <div className="col-sm-12 padTop10">
          <h2>{t(`habit.label.create_new`)}</h2>
        </div>
      </div>
      <HabitForm onSubmit={onSubmit(addHabit)} currentUser={currentUser} />
    </PageLayout>
  );
};

生活orm.web.jsx

const HabitForm = ({ values, handleSubmit, setFieldValue, submitting, t  }) => {
  const [habitType, sethabitType] = useState('Fitness Habits');
  const [intervalText, setIntervalText] = useState(t('habit.field.interval'));

  const [habitActions, sethabitActions] = useState([]);
  const [habitFreqs, sethabitFreqs] = useState([]);
  const [habitDurations, sethabitDurations] = useState([]);
  const [habitIntervals, sethabitIntervals] = useState([]);

  const [showInterval, setshowInterval] = useState(true);
  const [showHabitDiv, setshowHabitDiv] = useState(false);

  const [habitActionDisabled, sethabitActionDisabled] = useState(true);
  let calendarComponentRef = React.createRef();
  let calendarWeekends = true;
  let [calendarEvents, setCalendarEvents] = useState([]);

  var timeZones = moment.tz.names();

  const handleHabitTypeChange = (type, value, setFieldValue) => {
    setFieldValue(type, value);
    resetValues();
    Object.values(settings.habits.list).map(object => {
      if (object.habit_type == value) {
        const _habitActions = [];
        Object.values(object.habit_actions).map(object2 => {
          _habitActions.push(object2.title);
        });
        sethabitType(value);
        sethabitActions(_habitActions);
        setshowHabitDiv(false);
        sethabitActionDisabled(false);
      }
    });
  };

  const updateIntervalText = worktype => {
    if (worktype === 5) {
      setIntervalText(t('habit.field.number'));
    } else if (worktype === 6 || worktype === 7) {
      setIntervalText(t('habit.field.proof'));
    } else {
      setIntervalText(t('habit.field.interval'));
    }
  };

  const handleHabitActionChange = (type, value, setFieldValue) => {
    const preparedValue = Array.isArray(value) ? value[0] : value;
    setFieldValue(type, preparedValue);
    const _habitFreqs = [];
    const _habitDurations = [];
    const _habitIntervals = [];
    resetValues();
    Object.values(settings.habits.list).map(object => {
      if (object.habit_type == habitType) {
        Object.values(object.habit_actions).map(object2 => {
          if (object2.title == preparedValue) {
            Object.values(object2.duration).map(object4 => {
              _habitDurations.push(object4);
            });
            Object.values(object2.interval).map(object5 => {
              _habitIntervals.push(object5);
            });
            sethabitFreqs(_habitFreqs);
            sethabitIntervals(_habitIntervals);
            sethabitDurations(_habitDurations);
            setshowHabitDiv(true);
            setFieldValue('timezone', moment.tz.guess());
            setFieldValue('worktype', object2.worktype);
            setFieldValue('description', object2.description);
            setFieldValue('misc', JSON.stringify(object2.misc));
            updateIntervalText(object2.worktype);
          }
        });
      }
    });
  };

  const handleValueChange = (type, value, setFieldValue) => {
    const preparedValue = value;
    setFieldValue(type, preparedValue);
    let timezone = values.timezone;
    let interval = values.interval;
    let duration = values.duration;
    if (type === 'timezone') {
      timezone = value;
    } else if (type === 'interval') {
      interval = value;
    } else if (type === 'duration') {
      duration = value;
    }
    updateCalendarEvents(values.habit_action, timezone, interval, duration);
  };

  const empty = e => {
    switch (e) {
      case '':
      case 0:
      case '0':
      case null:
      case false:
      case typeof this == 'undefined':
        return true;
      default:
        return false;
    }
  };

  const resetValues = () => {
    values.duration = '';
    values.interval = '';
    values.timezone = '';
    updateCalendarEvents(values.habit_action, values.timezone, values.interval, values.duration);
  };

  const updateCalendarEvents = (habit_action, timezone, interval, duration) => {
    setCalendarEvents([]);
    let events = [];
    if (!empty(timezone) && !empty(interval) && !empty(duration)) {
      var dur = JSON.parse(duration);
      var int = JSON.parse(interval);
      var times = dur.count;
      var counter = 0;
      for (var i = 0; i < times; i++) {
        if (i % int.step === 0) {
          counter += 1;
          var obj = {
            title: values.habit_action + ' ' + int.title,
            start: moment
              .tz(values.timezone)
              .add(i + 1, 'days')
              .format(),
            allDay: true
          };
          let addObj = true;
          if (values.worktype === 7 && i === 0) {
            addObj = false;
          }
          if (dur.weekdays === true && (moment(obj.start).isoWeekday() === 6 || moment(obj.start).isoWeekday() === 7)) {
            addObj = false;
          }
          if (
            values.worktype === 7 &&
            counter > 2 &&
            counter < 10 &&
            (habit_action === 'Stay Alcohol Free' || (habit_action === 'Stay Nicotine Free' && dur.count === 28))
          ) {
            obj.start = moment
              .tz(values.timezone)
              .add(i + (counter - 1), 'days')
              .format();
            true;
          }
          if (addObj) {
            events.push(obj);
          }
        }
      }
      if (habit_action === 'Stay Alcohol Free' && dur.count === 28) {
        events.sort(function(a, b) {
          return moment(b.start) - moment(a.start);
        });
        events.shift();
        events.shift();
      }
      setCalendarEvents(events);
    }
  };
  if (settings.habits.list) {
    return (
      <div className="row">
        <div className="col-sm-5">
          <div className="card">
            <div className="card-body">
              <Form name="habit" onSubmit={handleSubmit}>
                <Field
                  name="habit_type"
                  component={RenderSelect}
                  type="select"
                  label={t('habit.field.habit_type')}
                  value={values.habit_type}
                  onChange={value => handleHabitTypeChange('habit_type', value, setFieldValue)}
                  cols={1}
                >
                  <Option value={0}>--Please Select--</Option>
                  {Object.values(settings.habits.list).map((object, i) => {
                    return (
                      <Option key={i} value={object.habit_type}>
                        {object.habit_type}
                      </Option>
                    );
                  })}
                </Field>

add.jsx

class HabitAdd extends React.Component {
  static propTypes = {
    currentUser: PropTypes.object
  };

  constructor(props) {
    super(props);
    this.subscription = null;
    this.state = { options: [] };
  }

  render() {
    if ( this.props.currentUser) {
      return <HabitAddView {...this.props} />;
    } else {
      return <div></div>;
    }
  }
}

export default compose(
  graphql(ADD_HABIT, {
    props: ({ ownProps: { history, navigation }, mutate }) => ({
      addHabit: async (
        habit_type,
        habit_action,
        duration,
        interval,
        timezone,
        description,
        worktype,
        misc,
        user_id
      ) => {
        let habitData = await mutate({
          variables: {
            input: {
              habit_type: habit_type,
              habit_action: habit_action,
              duration: duration,
              interval: interval,
              timezone: timezone,
              description: description,
              worktype: worktype,
              misc: misc,
              user_id: user_id
            }
          },
          optimisticResponse: {
            __typename: 'Mutation',
            addHabit: {
              __typename: 'Habit',
              id: null,
              habit_type: habit_type,
              habit_action: habit_action,
              duration: duration,
              interval: interval,
              timezone: timezone,
              description: description,
              worktype: worktype,
              misc: misc,
              user_id: user_id,
              days: [],
              bets: []
            }
          }
        });

        if (history) {
          window.location.href = window.location.origin + '/habit/' + habitData.data.addHabit.id;
        } else if (navigation) {
          return navigation.push('HabitEdit', { id: habitData.data.addHabit.id });
        }
      }
    })
  }),
  graphql(CURRENT_USER_QUERY, {
    props({ data: { error, currentUser } }) {
      if (error) throw new Error(error);
      return { currentUser };
    }
  })
)(HabitAdd);

多亏了埃斯,我才意识到我的错误。在渲染方法上添加了此代码行

render() {
    if ( this.props.currentUser) {
      return <HabitAddView {...this.props} />;
    } else {
      return <div></div>;
    }
  }

共有3个答案

常培
2023-03-14

这是在metro.config.js中启用InlineRequests时发生的。尝试禁用它并再次运行生成。。。

module.exports = {
  transformer: {
    getTransformOptions: async () => ({
      transform: {
        experimentalImportSupport: true,
        inlineRequires: false
      }
    })
  }
};
井翰
2023-03-14

VSCode在这里很有帮助。尝试在调试模式下运行节点应用程序,使用-检查选项,选中异常暂停选项。

或者,您可以考虑将应用程序配置为具有更长的堆栈跟踪,或者使用longjohn之类的工具[https://www.npmjs.com/package/longjohn]这有助于解决这个问题。

任绪
2023-03-14

问题在于当前用户。考虑初始化它。在布线之前,我假设您正在设置currentUser的值,或者currentUser正在设置一个值,但是在刷新时,该值被重置,尽管组件将加载,currentUser的值不可用,因此出现错误。

 类似资料:
  • 获取错误。我尝试做多个选择,并更改第二个选择的数据与第一个选择的上更改材料表行。我正在使用Firebase。 当“store.Urunler”为null或未定义时,我会出现此错误。而且我的产品没有列在菜单项上,这意味着选择是空的,但state.products有数据 我怎样才能克服这个错误。我还想添加到Urunler,选择一个输入。我知道我应该为onChanges调用函数,但如果它起作用,我以后会

  • 我正在我的反应应用程序中创建一个上一个和下一个按钮。我试图获取页面的当前索引(我有一个存储在对象中的页面列表) 这是密码 我得到的错误是“类型错误:无法将未定义或空转换为对象” 需要明确的是,imageName和images不是空的或未定义的(因为当I console.log它时,它有我需要的数据)。 提前谢谢!

  • 我编写了两个函数,可以有效地复制JSON.stringify(),将一系列值转换为stringify版本。当我将代码移植到JSBin并在一些示例值上运行它时,它运行得很好。但是我在一个专门为测试这个而设计的规范运行程序中遇到了这个错误。 我的代码: 我从测试人员那里得到的错误消息是: 它似乎失败了:例如stringifyJSON(null)

  • 我对Vue相当陌生,我一直在尝试如何使用Axios调用Java API。 vue.config.js dashboard.vue 然而,无论我如何尝试,它总是给出错误: 在这个错误中,我编辑了dashboard.vue:19的路径,但它来自那里。这行给出了错误:。 API运行在localhost端口8080上,Vue应用程序运行在localhost端口3000上。我不确定是我做错了跨原点还是完全不

  • 我的职能是: 我在这条线上出错了。 我们需要解决它。请帮忙做。

  • 我正在尝试根据表所获得的数据动态呈现表。这一部分是有效的,但是当我实现了数据的过滤版本时,我在行上得到了TypeError Undefined或Null to object错误。 以下是供参考的数据(目前只是一些模拟数据): 它在我添加部分之前工作,我将tableData直接传递到,我不知道为什么。有人能帮我吗?