Genesis 38:10

And the thing which he did displeased the LORD: wherefore he slew him also.

The Lord was displeased by what Onan did and for that reason put him to death also. That deed, identified as Onanism, was a breach of the law of chastity and an act of licentiousness, so that the divine judgment in the verse stands joined to the condemnation of licentious conduct. It is a kind of wrongdoing that may be wrongly looked upon as innocent.