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

Apollo Boost Mutation无响应问题求助(React+GraphQL场景)

Fixing Unresponsive Mutation in React-Apollo (Apollo Boost)

Hey there! I see you're new to React, GraphQL, and React-Apollo—let's figure out why your Mutation isn't responding and get it working smoothly. After going through your code, here are the key issues and actionable fixes:

1. You're Modifying State Directly in Render (A Critical Mistake)

Render should be a pure function—you never want to mutate this.state directly inside it. Right now, you're doing things like:

const fromDateTime = this.state.fromDt = Moment(this.state.date + " " + this.state.reservationTime).toISOString();

This breaks React's state management flow, leading to unpredictable values for your mutation variables (like fromDt and toDt). These invalid values might be stopping the mutation from firing entirely.

Fix: Calculate these time values either when dependent state changes (like date or reservationTime) or right before submitting the form. Add a dedicated method for this:

computeReservationTimes = () => {
  const fromDt = Moment(`${this.state.date} ${this.state.reservationTime}`).toISOString();
  const endTime = Moment.utc(Moment.utc(this.state.reservationTime, 'hh:mm A').add(40, 'm')).format('HH:mm');
  const toDt = Moment(`${this.state.date} ${endTime}`).toISOString();
  return { fromDt, toDt };
}

Call this method when you need the final time values (e.g., in your form submit handler).

2. Nested Forms Are Invalid HTML

You have a <form> nested inside another <form> in your render code:

<form onSubmit={e => { ... }}>
  <!-- ... -->
  <form className={classes.formControl} noValidate>
    <TextField id="date" ... />
  </form>
  <!-- ... -->
</form>

Nested forms aren't allowed in HTML—browsers ignore the inner form, which means your submit event might not trigger the mutation at all.

Fix: Replace the inner <form> with a <div> or other container element:

<div className={classes.formControl} noValidate>
  <TextField id="date" label="Date" type="date" className={classes.textField}
    InputLabelProps={{ shrink: true }}
    onChange={e => this.handleOnChange("date", e)} />
</div>

3. Missing/Incorrect handleChange Implementation

You bound handleChange but didn't include its code. Right now, your cart and timezone selects use handleChange, but if it's not updating state properly, those values will be empty or invalid when you run the mutation.

Fix: Make handleChange work the same way as handleOnChange:

handleChange = (e) => {
  this.setState({ [e.target.name]: e.target.value });
}

This ensures your cart and timezone state values update correctly when the user makes selections.

4. Invalid Variable Calculations (Like section)

Your current code uses classroom.substring(1, 1) to get the section—this will always return an empty string! That invalid parameter could cause your backend to reject the mutation.

Fix: Adjust the section/grade extraction to match your classroom format. For example, if classroom looks like "1A":

const section = classroom.charAt(1); // Gets "A"
const grade = parseInt(classroom.charAt(0), 10); // Gets 1

5. Add Explicit Debugging to Verify Variables

Before calling bookCart, log your variables to confirm they're valid. This helps catch unexpected empty or incorrect values:

onSubmit={e => {
  e.preventDefault();
  const { userId, classroom, cart } = this.state;
  const { fromDt, toDt } = this.computeReservationTimes();
  
  // Fix section/grade extraction
  const section = classroom.charAt(1);
  const grade = parseInt(classroom.charAt(0), 10);

  const variables = {
    rDateStart: fromDt,
    rDateEnd: toDt,
    grade,
    section,
    userId,
    cartlabId: cart
  };

  console.log('Submitting mutation with variables:', variables);

  bookCart({ variables })
    .then(res => console.log('Reservation successful!', res))
    .catch(err => console.error('Reservation failed:', err));
}}

Additional Debugging Tips

  • Check your browser's Network tab to see if the GraphQL request is being sent. If not, the issue is with the submit event or mutation setup.
  • Update your ApolloClient onError handler to log network errors:
    onError: ({ graphQLErrors, networkError }) => {
      if (graphQLErrors) console.log('GraphQL Errors:', graphQLErrors);
      if (networkError) console.log('Network Error:', networkError);
    }
    

Give these fixes a try—they should resolve the unresponsive mutation issue you're facing.

内容的提问来源于stack exchange,提问作者James David Bradly Carballo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:27:42