YMFE/yapi · error

context.href 不能被赋值

Error message

context.href 不能被赋值

What it means

In the postman/script sandbox, context is a frozen-ish object exposing URL parts as getters. Assigning to context.href is intentionally forbidden — href is derived from the request URL — so the setter always throws.

Source

Thrown at common/postmanLib.js:260

 * 
 * @param {*} defaultOptions 
 * @param {*} preScript 
 * @param {*} afterScript 
 * @param {*} commonContext  负责传递一些业务信息,crossRequest 不关注具体传什么,只负责当中间人
 */
async function crossRequest(defaultOptions, preScript, afterScript, commonContext = {}) {
  let options = Object.assign({}, defaultOptions);
  const taskId = options.taskId || Math.random() + '';
  let urlObj = URL.parse(options.url, true),
    query = {};
  query = Object.assign(query, urlObj.query);
  let context = {
    isNode,
    get href() {
      return urlObj.href;
    },
    set href(val) {
      throw new Error('context.href 不能被赋值');
    },
    get hostname() {
      return urlObj.hostname;
    },
    set hostname(val) {
      throw new Error('context.hostname 不能被赋值');
    },

    get caseId() {
      return options.caseId;
    },

    set caseId(val) {
      throw new Error('context.caseId 不能被赋值');
    },

    method: options.method,
    pathname: urlObj.pathname,

View on GitHub (pinned to 59bade3a8a)

Solutions

  1. Remove any assignment to context.href from your script
  2. Use context.url or the request configuration to change the target before the request, not context.href
  3. Read context.href if you only need the current URL

Example fix

// before
context.href = 'http://newhost/api';
// after
// do not mutate href; use request URL config instead
console.log(context.href);
Defensive patterns

Strategy: type-guard

Validate before calling

if (Object.getOwnPropertyDescriptor(context, 'href') && context.href === wantedUrl) { /* already correct, skip */ }

Type guard

function canSet(obj, key){ const d = Object.getOwnPropertyDescriptor(obj, key); return !!d && typeof d.set === 'function' && !/不能被赋值/.test(String(d.set)); }

Try / catch

try {
  context.href = newUrl;
} catch (e) {
  console.warn('context is read-only; change request URL in case config instead');
}

Prevention

When it happens

Trigger: A test/script (assert or script sandbox) contains code like context.href = 'http://...' during interface case execution.

Common situations: Scripts ported from Postman where setting request URL via variables; users trying to redirect the request inside a script; generated script templates that mutate context.

Related errors


AI-assisted analysis of YMFE/yapi@59bade3a8a (2026-08-29). Data as JSON: /api/errors/b8864fe0e6fa1fbc. Report an issue: GitHub.