Error arrow function should not return assignment no return assign

My code is working correctly in the app however, my eslint isn't liking it and is saying I should not return assignment. What is wrong with this?
this.myCustomEl = el} />

The Fix:

<div ref={(el) => { this.myCustomEl = el }} />

The Explanation:

Your current code is equivalent to:

<div ref={(el) => { return this.myCustomEl = el }} />

You are returning the result of this.myCustomEl = el. In your code, this is not really a problem — however, one of the most frustrating bugs in programming occurs when you accidentally use an assignment (=) instead of a comparator (== or ===), for instance:

// This function will always return **true**, surprisingly
function isEqual(a, b) {
  // The warning would be thrown here, because you probably meant to type "a===b". The below function will always return true;
  return a=b;
}

let k=false;
let j=true;

if(isEqual(k,j)){
  // You'll be very, very, very confused as to why this code is reached because you literally just set k to be false and j to be true, so they should be different, right? Right?
  thisWillExecuteUnexpectedly();
}

In the above case, the compiler warning makes sense because k=true evaluates to true (as opposed to k===true, which is probably what you meant to type) and causes unintended behavior. Thus, eshint notices when you return an assignment, assumes that you meant to return a comparison, and lets you know that you should be careful.

In your case, you can solve this by simply not returning the result, which is done by adding enclosing brackets {} and no return statement:

<div ref={(el) => { this.myCustomEl = el }} />

You can also adjust the eshint warning like so:
https://eslint.org/docs/rules/no-return-assign

Disallow assignment operators in return statements

One of the interesting, and sometimes confusing, aspects of JavaScript is that assignment can happen at almost any point. Because of this, an errant equals sign can end up causing assignment when the true intent was to do a comparison. This is especially true when using a return statement. For example:

function doSomething() {
    return foo = bar + 2;
}

It is difficult to tell the intent of the return statement here. It’s possible that the function is meant to return the result of bar + 2, but then why is it assigning to foo? It’s also possible that the intent was to use a comparison operator such as == and that this code is an error.

Because of this ambiguity, it’s considered a best practice to not use assignment in return statements.

Rule Details

This rule aims to eliminate assignments from return statements. As such, it will warn whenever an assignment is found as part of return.

Options

The rule takes one option, a string, which must contain one of the following values:

  • except-parens (default): Disallow assignments unless they are enclosed in parentheses.
  • always: Disallow all assignments.

except-parens

This is the default option.
It disallows assignments unless they are enclosed in parentheses.

Examples of incorrect code for the default "except-parens" option:

/*eslint no-return-assign: "error"*/

function doSomething() {
    return foo = bar + 2;
}

function doSomething() {
    return foo += 2;
}

const foo = (a, b) => a = b

const bar = (a, b, c) => (a = b, c == b)

function doSomething() {
    return foo = bar && foo > 0;
}

Examples of correct code for the default "except-parens" option:

/*eslint no-return-assign: "error"*/

function doSomething() {
    return foo == bar + 2;
}

function doSomething() {
    return foo === bar + 2;
}

function doSomething() {
    return (foo = bar + 2);
}

const foo = (a, b) => (a = b)

const bar = (a, b, c) => ((a = b), c == b)

function doSomething() {
    return (foo = bar) && foo > 0;
}

always

This option disallows all assignments in return statements.
All assignments are treated as problems.

Examples of incorrect code for the "always" option:

/*eslint no-return-assign: ["error", "always"]*/

function doSomething() {
    return foo = bar + 2;
}

function doSomething() {
    return foo += 2;
}

function doSomething() {
    return (foo = bar + 2);
}

Examples of correct code for the "always" option:

/*eslint no-return-assign: ["error", "always"]*/

function doSomething() {
    return foo == bar + 2;
}

function doSomething() {
    return foo === bar + 2;
}

When Not To Use It

If you want to allow the use of assignment operators in a return statement, then you can safely disable this rule.

Version

This rule was introduced in ESLint v0.0.9.

Resources

  • Rule source
  • Tests source

Please note that some of the suggested workarounds (adding parens/curlies around the expression) may conflict with other rules, such as no-extra-parens, brace-style (1tbs) and/or semi.

Example:

/*eslint no-return-assign: 2,
         no-extra-parens: 2,
         brace-style: 2,
         semi: 2
*/

somePromise.then(foo => foo.bar = 1);

As expected, the above code fails with:

error  Arrow function should not return assignment  no-return-assign

Workaround 1: Wrap the assignment expression in parens:

/*eslint no-return-assign: 2,
         no-extra-parens: 2,
         brace-style: 2,
         semi: 2
*/

somePromise.then(foo => (foo.bar = 1));

We now fail with:

error  Gratuitous parentheses around expression     no-extra-parens

Workaround 2: Wrap the assignment expression in curlies:

/*eslint no-return-assign: 2,
         no-extra-parens: 2,
         brace-style: 2,
         semi: 2
*/

somePromise.then(foo => {foo.bar = 1});

We now fail with:

error  Statement inside of curly braces should be on next line  brace-style
error  Missing semicolon                                        semi

The semi error could be mitigated by including omitLastInOneLineBlock: true; but it would still violate the 1tbs brace style

Workaround 3: Convert from concise body to full block body:

/*eslint no-return-assign: 2,
         no-extra-parens: 2,
         brace-style: 2,
         semi: 2
*/

somePromise.then(foo => {
  foo.bar = 1;
});

Success! Although I would argue that the arrow function has lost some of it’s original beauty here.

Based on this, I don’t think any of the suggested workarounds (except perhaps temporarily disabling, via eslint-disable) are particularly appealing, considering their impact on other rules.

If you’re still interested in votes for some kind of exception to the rule; consider this my +1.

Arrow function should not return assignment no return assignment.

This paper describes the problems encountered in learning p221 of the latest Vue and vuejs in 2019, from introduction to mastery. Because the checking code of eslint is referenced, the checking error is reported. There is no problem with the code, it is the problem of eslint checking.
Solutions: 1. Remove eslint
2. Modify the code to conform to eslint
original code

   if (this.isSelectAll) {
        this.cartList.forEach(item => item.checked = false)
      } else {
        this.cartList.forEach(item => item.checked = true)
      }

Changed code

   if (this.isSelectAll) {
        this.cartList.forEach(item => { item.checked = false })
      } else {
        this.cartList.forEach(item => { item.checked = true })
      }

After learning the arrow function, we can know that the {} added can be omitted, but the rule of eslint requires this.

Read More:

  • Under the “return-d” mode, the number of “return / return” is 1
  • Solve the problem of flag error valueerror: View function did not return a response
  • error: ‘::main’ must return ‘int’
  • C++ —Return multiple values of different types
  • Python TypeError: return arrays must be of ArrayType
  • Error executing Aidl: return code 1
  • Vs + CUDA compilation error: msb3721, return code 255
  • Waitpid call return error prompt: no child processes problem
  • How Notepad + + displays all characters (for hidden carriage return spaces)
  • [Android test] solution for error closed after the carriage return of the ADB shell
  • error Expected an assignment or function call and instead saw an expression
  • To solve the problem, start eclipse and return exit code = 13
  • [Solved] hiveonspark:Execution Error, return code 30041 from org.apache.hadoop.hive.ql.exec.spark.SparkTask
  • An error is reported in the idea editor missing return statement
  • Execution error, return code 1 from org.apache.hadoop . hive.ql.exec .DDLTask.
  • Failed: execution error, return code 1 from org.apache.hadoop . hive.ql.exec .DDLTask…
  • python reads csv file is an error _csv.Error: iterator should return strings, not bytes (did you open the file in text)
  • [Transfer] mdt wds deployment windows Litetouch deployment failed, Return Code = -2147467259 0x80004005 solution…
  • mdt wds deployment windows Litetouch deployment failed, Return Code = -2147467259 0x80004005
  • FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. MetaException(me

Disallow assignment operators in return statements

One of the interesting, and sometimes confusing, aspects of JavaScript is that assignment can happen at almost any point. Because of this, an errant equals sign can end up causing assignment when the true intent was to do a comparison. This is especially true when using a return statement. For example:

function doSomething() {    return foo = bar + 2;}

It is difficult to tell the intent of the return statement here. It’s possible that the function is meant to return the result of bar + 2, but then why is it assigning to foo? It’s also possible that the intent was to use a comparison operator such as == and that this code is an error.

Because of this ambiguity, it’s considered a best practice to not use assignment in return statements.

Rule Details

This rule aims to eliminate assignments from return statements. As such, it will warn whenever an assignment is found as part of return.

Options

The rule takes one option, a string, which must contain one of the following values:

  • except-parens (default): Disallow assignments unless they are enclosed in parentheses.
  • always: Disallow all assignments.

except-parens

This is the default option. It disallows assignments unless they are enclosed in parentheses.

Examples of incorrect code for the default "except-parens" option:

function doSomething() {    return foo = bar + 2;}function doSomething() {    return foo += 2;}const foo = (a, b) => a = bconst bar = (a, b, c) => (a = b, c == b)function doSomething() {    return foo = bar && foo > 0;}

Examples of correct code for the default "except-parens" option:

function doSomething() {    return foo == bar + 2;}function doSomething() {    return foo === bar + 2;}function doSomething() {    return (foo = bar + 2);}const foo = (a, b) => (a = b)const bar = (a, b, c) => ((a = b), c == b)function doSomething() {    return (foo = bar) && foo > 0;}

always

This option disallows all assignments in return statements. All assignments are treated as problems.

Examples of incorrect code for the "always" option:

/*eslint no-return-assign: ["error", "always"]*/function doSomething() {    return foo = bar + 2;}function doSomething() {    return foo += 2;}function doSomething() {    return (foo = bar + 2);}

Examples of correct code for the "always" option:

/*eslint no-return-assign: ["error", "always"]*/function doSomething() {    return foo == bar + 2;}function doSomething() {    return foo === bar + 2;}

When Not To Use It

If you want to allow the use of assignment operators in a return statement, then you can safely disable this rule.

Version

This rule was introduced in ESLint v0.0.9.

Resources

  • Rule source
  • Tests source


ESLint

8.30

  • no-restricted-properties

    Disallow certain properties on objects Certain properties on objects may be disallowed codebase.

  • no-restricted-syntax

    Disallow specified syntax JavaScript has lot of language features, and not everyone likes all them.

  • no-return-await

    Disallow unnecessary return await Using return await inside an async function keeps the current call stack until Promise that being awaited has resolved,

  • no-script-url

    Disallow javascript: urls Using javascript: URLs is considered by some form of eval.

Вера Брусницына

здравствуйте! Решение прошло, но при чистке линтера выдаются ошибки

error Arrow function should not return assignment no-return-assign

error Assignment to function parameter ‘total’ no-param-reassign
вычисляю кол-во единиц в массиве:

const amount1 = arr.flat().reduce((total, item) => ((item === 1) ? total += 1 : total), 0);

Одно связано со знаком присваивания в return, другое с параметром total типа не стоит изменять. Меняла calldack из стрелочной в обычную — еще больше ошибок


2


0

Roman Ashikov

Приветствую, Вера!

Используя оператор присваивания со сложением вы напрямую мутируете параметр (no-param-reassign) total, а тернарный оператор возвращает значение в зависимости от условия и таким образом появляется вторая ошибка — no-return-assign.

Важно понять, что изменение аккумулятора при переходе к следующему элементу массива происходит внутри reduce(). Нужно лишь вернуть какое-то значение из колбека. Взгляните на такой пример:

const coll = [1, 1, 1, 1, 1];
coll.reduce((acc, item) => acc + item, 0); // 5

Как видите явно переопределять acc нет необходимости. А вот цитата о аккумуляторе из документации MDN:

Аккумулятор, аккумулирующий значение, которое возвращает функция callback после посещения очередного элемента…


0

Вера Брусницына

Роман Ашиков, Спасибо, действительно, я уже этим пользовалась и забыла суть функции reduce.


0

Two choices.

Temporarily disable warning

(Untested; and there are multiple ways to do this.)

// eslint-disable-next-line react/prefer-stateless-function
export class myComponent extends React.Component {
  ...
}

Use a pure stateless component

The return value is what will be rendered (e.g., you’re basically writing class-based component’s render method:

export const myComponent = () => {
  return (
    // JSX here
  )
}

(Or use non-ES6 notation if that’s your thing.)

For components like this with no other supporting logic I prefer the implicit return, e.g.,

export MyComponent = () =>
  <div>
    // Stuff here
  </div>

This is a matter of preference. I would say that you should follow React naming conventions, though, and keep all components starting with an upper-case letter.

ESLint may complain about missing parens around a multi-line JSX expressions, so disable that rule or use parens.

If you need props, they’re passed in as the argument to the function:

const MyComponent = (props) =>
  <div>
    <Something someProp={props.foo} />
  </div>

export MyComponent

And you can destructure in the parameter as usual for convenience:

const MyComponent = ({ foo }) =>
  <div>
    <Something someProp={foo} />
  </div>

This can make the implicit return a little easier if you were using local vars. You’ll get an ESLint warning about missing PropTypes unless you declare them; since it’s not a class you cannot simply use static propTypes in the class, they must be attached to the function (which many people prefer anyway).

Понравилась статья? Поделить с друзьями:
  • Error array variable has incorrect number of subscripts or subscript dimension range exceeded
  • Error base 1003
  • Error array used as initializer
  • Error bars что это
  • Error array type has incomplete element type